]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/staging/rspiusb/rspiusb.c
Staging: rspiusb: clean rspiusb code
[karo-tx-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 /**
202  *      piusb_ioctl
203  */
204 static int piusb_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
205                        unsigned long arg)
206 {
207         struct device_extension *pdx;
208         char dummyCtlBuf[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
209         unsigned long devRB = 0;
210         int i = 0;
211         int err = 0;
212         int retval = 0;
213         struct ioctl_struct ctrl;
214         unsigned char *uBuf;
215         int numbytes = 0;
216         unsigned short controlData = 0;
217
218         pdx = (struct device_extension *)file->private_data;
219         /* verify that the device wasn't unplugged */
220         if (!pdx->present) {
221                 dbg("No Device Present\n");
222                 return -ENODEV;
223         }
224         /* fill in your device specific stuff here */
225         if (_IOC_DIR(cmd) & _IOC_READ)
226                 err = !access_ok(VERIFY_WRITE, (void __user *)arg,
227                                 _IOC_SIZE(cmd));
228         else if (_IOC_DIR(cmd) & _IOC_WRITE)
229                 err = !access_ok(VERIFY_READ, (void __user *)arg,
230                                _IOC_SIZE(cmd));
231         if (err) {
232                 dev_err(&pdx->udev->dev, "return with error = %d\n", err);
233                 return -EFAULT;
234         }
235         switch (cmd) {
236         case PIUSB_GETVNDCMD:
237                 if (copy_from_user
238                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
239                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
240                 dbg("%s %x\n", "Get Vendor Command = ", ctrl.cmd);
241                 retval =
242                     usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
243                                     ctrl.cmd, USB_DIR_IN, 0, 0, &devRB,
244                                     ctrl.numbytes, HZ * 10);
245                 if (ctrl.cmd == 0xF1) {
246                         dbg("FW Version returned from HW = %ld.%ld",
247                             (devRB >> 8), (devRB & 0xFF));
248                 }
249                 if (retval >= 0)
250                         retval = (int)devRB;
251                 return retval;
252
253         case PIUSB_SETVNDCMD:
254                 if (copy_from_user
255                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
256                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
257                 /* dbg( "%s %x", "Set Vendor Command = ",ctrl.cmd ); */
258                 controlData = ctrl.pData[0];
259                 controlData |= (ctrl.pData[1] << 8);
260                 /* dbg( "%s %d", "Vendor Data =",controlData ); */
261                 retval = usb_control_msg(pdx->udev,
262                                 usb_sndctrlpipe(pdx->udev, 0),
263                                 ctrl.cmd,
264                                 (USB_DIR_OUT | USB_TYPE_VENDOR
265                                  /* | USB_RECIP_ENDPOINT */),
266                                 controlData, 0,
267                                 &dummyCtlBuf, ctrl.numbytes, HZ * 10);
268                 return retval;
269
270         case PIUSB_ISHIGHSPEED:
271                 return ((pdx->udev->speed == USB_SPEED_HIGH) ? 1 : 0);
272
273         case PIUSB_WRITEPIPE:
274                 if (copy_from_user(&ctrl, (void __user *)arg, _IOC_SIZE(cmd)))
275                         dev_err(&pdx->udev->dev,
276                                         "copy_from_user WRITE_DUMMY failed\n");
277                 if (!access_ok(VERIFY_READ, ctrl.pData, ctrl.numbytes)) {
278                         dbg("can't access pData");
279                         return 0;
280                 }
281                 piusb_output(&ctrl, ctrl.pData /* uBuf */, ctrl.numbytes, pdx);
282                 return ctrl.numbytes;
283
284         case PIUSB_USERBUFFER:
285                 if (copy_from_user
286                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
287                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
288                 return MapUserBuffer((struct ioctl_struct *) &ctrl, pdx);
289
290         case PIUSB_UNMAP_USERBUFFER:
291                 retval = UnMapUserBuffer(pdx);
292                 return retval;
293
294         case PIUSB_READPIPE:
295                 if (copy_from_user
296                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
297                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
298                 switch (ctrl.endpoint) {
299                 case 0: /* ST133 Pixel Data or PIXIS IO */
300                         if (pdx->iama == PIXIS_PID) {
301                                 unsigned int numToRead = 0;
302                                 unsigned int totalRead = 0;
303                                 uBuf = kmalloc(ctrl.numbytes, GFP_KERNEL);
304                                 if (!uBuf) {
305                                         dbg("Alloc for uBuf failed");
306                                         return 0;
307                                 }
308                                 numbytes = ctrl.numbytes;
309                                 numToRead = numbytes;
310                                 dbg("numbytes to read = %d", numbytes);
311                                 dbg("endpoint # %d", ctrl.endpoint);
312                                 if (copy_from_user(uBuf, ctrl.pData, numbytes))
313                                         dbg("copying ctrl.pData to dummyBuf failed");
314                                 do {
315                                         i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl.endpoint], (uBuf + totalRead), (numToRead > 64) ? 64 : numToRead, &numbytes, HZ * 10);        /* EP0 can only handle 64 bytes at a time */
316                                         if (i) {
317                                                 dbg("CMD = %s, Address = 0x%02X", ((uBuf[3] == 0x02) ? "WRITE" : "READ"), uBuf[1]);
318                                                 dbg("Number of bytes Attempted to read = %d", (int)ctrl.numbytes);
319                                                 dbg("Blocking ReadI/O Failed with status %d", i);
320                                                 kfree(uBuf);
321                                                 return -1;
322                                         }
323                                         dbg("Pixis EP0 Read %d bytes",
324                                                         numbytes);
325                                         totalRead += numbytes;
326                                         numToRead -= numbytes;
327                                 } while (numToRead);
328                                 memcpy(ctrl.pData, uBuf, totalRead);
329                                 dbg("Total Bytes Read from PIXIS EP0 = %d",
330                                     totalRead);
331                                 ctrl.numbytes = totalRead;
332                                 if (copy_to_user
333                                     ((struct ioctl_struct *) arg, &ctrl,
334                                      sizeof(struct ioctl_struct)))
335                                         dbg("copy_to_user failed in IORB");
336                                 kfree(uBuf);
337                                 return ctrl.numbytes;
338                         }
339                         /* ST133 Pixel Data */
340                         if (!pdx->gotPixelData)
341                                 return 0;
342                         pdx->gotPixelData = 0;
343                         ctrl.numbytes = pdx->bulk_in_size_returned;
344                         pdx->bulk_in_size_returned -= pdx->frameSize;
345                         for (i = 0; i < pdx->maplist_numPagesMapped[pdx->active_frame]; i++)
346                                 SetPageDirty(pdx->sgl[pdx->active_frame][i].page_link);
347                         pdx->active_frame = ((pdx->active_frame + 1)
348                                         % pdx->num_frames);
349                         return ctrl.numbytes;
350
351                 case 1: /* ST133IO */
352                         /* fall through */
353                 case 4: /* PIXIS IO */
354                         uBuf = kmalloc(ctrl.numbytes, GFP_KERNEL);
355                         if (!uBuf) {
356                                 dbg("Alloc for uBuf failed");
357                                 return 0;
358                         }
359                         numbytes = ctrl.numbytes;
360                         /* dbg( "numbytes to read = %d", numbytes ); */
361                         if (copy_from_user(uBuf, ctrl.pData, numbytes))
362                                 dbg("copying ctrl.pData to dummyBuf failed");
363                         i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl.endpoint],
364                                          uBuf, numbytes, &numbytes, HZ * 10);
365                         if (i) {
366                                 dbg("Blocking ReadI/O Failed with status %d",
367                                     i);
368                                 kfree(uBuf);
369                                 return -1;
370                         }
371                         ctrl.numbytes = numbytes;
372                         memcpy(ctrl.pData, uBuf, numbytes);
373                         if (copy_to_user((struct ioctl_struct *) arg, &ctrl,
374                                                 sizeof(struct ioctl_struct)))
375                                 dbg("copy_to_user failed in IORB");
376                         kfree(uBuf);
377                         return ctrl.numbytes;
378
379                 case 2: /* PIXIS Ping */
380                         /* fall through */
381                 case 3: /* PIXIS Pong */
382                         if (!pdx->gotPixelData)
383                                 return 0;
384                         pdx->gotPixelData = 0;
385                         ctrl.numbytes = pdx->bulk_in_size_returned;
386                         pdx->bulk_in_size_returned -= pdx->frameSize;
387                         for (i = 0; i < pdx->maplist_numPagesMapped[pdx->active_frame]; i++)
388                                 SetPageDirty(pdx->sgl[pdx->active_frame][i].page_link);
389                         pdx->active_frame =
390                                 ((pdx->active_frame + 1) % pdx->num_frames);
391                         return ctrl.numbytes;
392
393                 default:
394                         break;
395                 }
396                 break;
397
398         case PIUSB_WHATCAMERA:
399                 return pdx->iama;
400
401         case PIUSB_SETFRAMESIZE:
402                 dbg("PIUSB_SETFRAMESIZE");
403                 if (copy_from_user
404                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
405                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
406                 pdx->frameSize = ctrl.numbytes;
407                 pdx->num_frames = ctrl.numFrames;
408                 if (!pdx->sgl)
409                         pdx->sgl =
410                             kmalloc(sizeof(struct scatterlist *) *
411                                     pdx->num_frames, GFP_KERNEL);
412                 if (!pdx->sgEntries)
413                         pdx->sgEntries =
414                             kmalloc(sizeof(unsigned int) * pdx->num_frames,
415                                     GFP_KERNEL);
416                 if (!pdx->PixelUrb)
417                         pdx->PixelUrb =
418                             kmalloc(sizeof(struct urb **) * pdx->num_frames,
419                                     GFP_KERNEL);
420                 if (!pdx->maplist_numPagesMapped)
421                         pdx->maplist_numPagesMapped =
422                             vmalloc(sizeof(unsigned int) * pdx->num_frames);
423                 if (!pdx->pendedPixelUrbs)
424                         pdx->pendedPixelUrbs =
425                             kmalloc(sizeof(char *) * pdx->num_frames,
426                                     GFP_KERNEL);
427                 return 0;
428
429         default:
430                 dbg("%s\n", "No IOCTL found");
431                 break;
432
433         }
434         /* return that we did not understand this ioctl call */
435         dbg("Returning -ENOTTY");
436         return -ENOTTY;
437 }
438
439 static void piusb_write_bulk_callback(struct urb *urb)
440 {
441         struct device_extension *pdx = urb->context;
442         int status = urb->status;
443
444         /* sync/async unlink faults aren't errors */
445         if (status && !(status == -ENOENT || status == -ECONNRESET))
446                 dev_dbg(&urb->dev->dev,
447                         "%s - nonzero write bulk status received: %d",
448                         __func__, status);
449
450         pdx->pendingWrite = 0;
451         usb_buffer_free(urb->dev, urb->transfer_buffer_length,
452                         urb->transfer_buffer, urb->transfer_dma);
453 }
454
455 int piusb_output(struct ioctl_struct *io, unsigned char *uBuf, int len,
456                  struct device_extension *pdx)
457 {
458         struct urb *urb = NULL;
459         int err = 0;
460         unsigned char *kbuf = NULL;
461
462         urb = usb_alloc_urb(0, GFP_KERNEL);
463         if (urb != NULL) {
464                 kbuf =
465                     usb_buffer_alloc(pdx->udev, len, GFP_KERNEL,
466                                      &urb->transfer_dma);
467                 if (!kbuf) {
468                         dev_err(&pdx->udev->dev, "buffer_alloc failed\n");
469                         return -ENOMEM;
470                 }
471                 memcpy(kbuf, uBuf, len);
472                 usb_fill_bulk_urb(urb, pdx->udev, pdx->hEP[io->endpoint], kbuf,
473                                   len, piusb_write_bulk_callback, pdx);
474                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
475                 err = usb_submit_urb(urb, GFP_KERNEL);
476                 if (err) {
477                         dev_err(&pdx->udev->dev,
478                                 "WRITE ERROR:submit urb error = %d\n", err);
479                 }
480                 pdx->pendingWrite = 1;
481                 usb_free_urb(urb);
482         }
483         return -EINPROGRESS;
484 }
485
486 static int UnMapUserBuffer(struct device_extension *pdx)
487 {
488         int i = 0;
489         int k = 0;
490         unsigned int epAddr;
491
492         for (k = 0; k < pdx->num_frames; k++) {
493                 dbg("Killing Urbs for Frame %d", k);
494                 for (i = 0; i < pdx->sgEntries[k]; i++) {
495                         usb_kill_urb(pdx->PixelUrb[k][i]);
496                         usb_free_urb(pdx->PixelUrb[k][i]);
497                         pdx->pendedPixelUrbs[k][i] = 0;
498                 }
499                 dbg("Urb error count = %d", errCnt);
500                 errCnt = 0;
501                 dbg("Urbs free'd and Killed for Frame %d", k);
502         }
503
504         for (k = 0; k < pdx->num_frames; k++) {
505                 if (pdx->iama == PIXIS_PID)
506                         /* which EP should we map this frame to ? */
507                         /* PONG, odd frames: hEP[3] */
508                         /* PING, even frames and zero hEP[2] */
509                         epAddr = (k % 2) ? pdx->hEP[3] : pdx->hEP[2];
510                 else
511                         /* ST133 only has 1 endpoint for Pixel data transfer */
512                         epAddr = pdx->hEP[0];
513
514                 usb_buffer_unmap_sg(pdx->udev, epAddr, pdx->sgl[k],
515                                     pdx->maplist_numPagesMapped[k]);
516                 for (i = 0; i < pdx->maplist_numPagesMapped[k]; i++)
517                         page_cache_release(pdx->sgl[k][i].page_link);
518                 kfree(pdx->sgl[k]);
519                 kfree(pdx->PixelUrb[k]);
520                 kfree(pdx->pendedPixelUrbs[k]);
521                 pdx->sgl[k] = NULL;
522                 pdx->PixelUrb[k] = NULL;
523                 pdx->pendedPixelUrbs[k] = NULL;
524         }
525
526         kfree(pdx->sgEntries);
527         vfree(pdx->maplist_numPagesMapped);
528         pdx->sgEntries = NULL;
529         pdx->maplist_numPagesMapped = NULL;
530         kfree(pdx->sgl);
531         kfree(pdx->pendedPixelUrbs);
532         kfree(pdx->PixelUrb);
533         pdx->sgl = NULL;
534         pdx->pendedPixelUrbs = NULL;
535         pdx->PixelUrb = NULL;
536
537         return 0;
538 }
539
540 static void piusb_readPIXEL_callback(struct urb *urb)
541 {
542         int i = 0;
543         struct device_extension *pdx = urb->context;
544         int status = urb->status;
545
546         if (status && !(status == -ENOENT || status == -ECONNRESET)) {
547                 dbg("%s - nonzero read bulk status received: %d", __func__,
548                     status);
549                 dbg("Error in read EP2 callback");
550                 dbg("FrameIndex = %d", pdx->frameIdx);
551                 dbg("Bytes received before problem occurred = %d",
552                     pdx->bulk_in_byte_trk);
553                 dbg("Urb Idx = %d", pdx->urbIdx);
554                 pdx->pendedPixelUrbs[pdx->frameIdx][pdx->urbIdx] = 0;
555         } else {
556                 pdx->bulk_in_byte_trk += urb->actual_length;
557                 i = usb_submit_urb(urb, GFP_ATOMIC);    /* resubmit the URB */
558                 if (i) {
559                         errCnt++;
560                         if (i != lastErr) {
561                                 dbg("submit urb in callback failed "
562                                                 "with error code %d", i);
563                                 lastErr = i;
564                         }
565                 } else {
566                         pdx->urbIdx++; /* point to next URB when we callback */
567                         if (pdx->bulk_in_byte_trk >= pdx->frameSize) {
568                                 pdx->bulk_in_size_returned =
569                                         pdx->bulk_in_byte_trk;
570                                 pdx->bulk_in_byte_trk = 0;
571                                 pdx->gotPixelData = 1;
572                                 pdx->frameIdx =
573                                         ((pdx->frameIdx +
574                                           1) % pdx->num_frames);
575                                 pdx->urbIdx = 0;
576                         }
577                 }
578         }
579 }
580
581 /* MapUserBuffer(
582         inputs:
583         struct ioctl_struct *io - structure containing user address,
584                                 frame #, and size
585         struct device_extension *pdx - the PIUSB device extension
586
587         returns:
588         int - status of the task
589
590         Notes:
591         MapUserBuffer maps a buffer passed down through an ioctl.
592         The user buffer is Page Aligned by the app and then passed down.
593         The function get_free_pages(...) does the actual mapping of the buffer
594         from user space to kernel space.
595         From there a scatterlist is created from all the pages.
596         The next function called is to usb_buffer_map_sg which allocated
597         DMA addresses for each page, even coalescing them if possible.
598         The DMA address is placed in the scatterlist structure.
599         The function returns the number of DMA addresses.
600         This may or may not be equal to the number of pages that
601         the user buffer uses.
602         We then build an URB for each DMA address and then submit them.
603 */
604
605 /*
606 int MapUserBuffer(unsigned long uaddr, unsigned long numbytes,
607                 unsigned long frameInfo, struct device_extension *pdx)
608 */
609 static int MapUserBuffer(struct ioctl_struct *io, struct device_extension *pdx)
610 {
611         unsigned long uaddr;
612         unsigned long numbytes;
613         int frameInfo;  /* which frame we're mapping */
614         unsigned int epAddr = 0;
615         unsigned long count = 0;
616         int i = 0;
617         int k = 0;
618         int err = 0;
619         struct page **maplist_p;
620         int numPagesRequired;
621
622         frameInfo = io->numFrames;
623         uaddr = (unsigned long)io->pData;
624         numbytes = io->numbytes;
625
626         if (pdx->iama == PIXIS_PID) {
627                 /* which EP should we map this frame to ? */
628                 /* PONG, odd frames: hEP[3] */
629                 /* PING, even frames and zero hEP[2] */
630                 epAddr = (frameInfo % 2) ? pdx->hEP[3] : pdx->hEP[2];
631                 dbg("Pixis Frame #%d: EP=%d", frameInfo,
632                     (epAddr == pdx->hEP[2]) ? 2 : 4);
633         } else { /* ST133 only has 1 endpoint for Pixel data transfer */
634                 epAddr = pdx->hEP[0];
635                 dbg("ST133 Frame #%d: EP=2", frameInfo);
636         }
637         count = numbytes;
638         dbg("UserAddress = 0x%08lX", uaddr);
639         dbg("numbytes = %d", (int)numbytes);
640
641         /* number of pages to map the entire user space DMA buffer */
642         numPagesRequired =
643             ((uaddr & ~PAGE_MASK) + count + ~PAGE_MASK) >> PAGE_SHIFT;
644         dbg("Number of pages needed = %d", numPagesRequired);
645         maplist_p = vmalloc(numPagesRequired * sizeof(struct page));
646         if (!maplist_p) {
647                 dbg("Can't Allocate Memory for maplist_p");
648                 return -ENOMEM;
649         }
650
651         /* map the user buffer to kernel memory */
652         down_write(&current->mm->mmap_sem);
653         pdx->maplist_numPagesMapped[frameInfo] = get_user_pages(current,
654                         current->mm, (uaddr & PAGE_MASK), numPagesRequired,
655                         WRITE, 0 /* Don't Force*/, maplist_p, NULL);
656         up_write(&current->mm->mmap_sem);
657         dbg("Number of pages mapped = %d",
658             pdx->maplist_numPagesMapped[frameInfo]);
659
660         for (i = 0; i < pdx->maplist_numPagesMapped[frameInfo]; i++)
661                 flush_dcache_page(maplist_p[i]);
662         if (!pdx->maplist_numPagesMapped[frameInfo]) {
663                 dbg("get_user_pages() failed");
664                 vfree(maplist_p);
665                 return -ENOMEM;
666         }
667
668         /* need to create a scatterlist that spans each frame
669          * that can fit into the mapped buffer
670          */
671         pdx->sgl[frameInfo] =
672             kmalloc((pdx->maplist_numPagesMapped[frameInfo] *
673                      sizeof(struct scatterlist)), GFP_ATOMIC);
674         if (!pdx->sgl[frameInfo]) {
675                 vfree(maplist_p);
676                 dbg("can't allocate mem for sgl");
677                 return -ENOMEM;
678         }
679         pdx->sgl[frameInfo][0].page_link = maplist_p[0];
680         pdx->sgl[frameInfo][0].offset = uaddr & ~PAGE_MASK;
681         if (pdx->maplist_numPagesMapped[frameInfo] > 1) {
682                 pdx->sgl[frameInfo][0].length =
683                     PAGE_SIZE - pdx->sgl[frameInfo][0].offset;
684                 count -= pdx->sgl[frameInfo][0].length;
685                 for (k = 1; k < pdx->maplist_numPagesMapped[frameInfo]; k++) {
686                         pdx->sgl[frameInfo][k].offset = 0;
687                         pdx->sgl[frameInfo][k].page_link = maplist_p[k];
688                         pdx->sgl[frameInfo][k].length =
689                             (count < PAGE_SIZE) ? count : PAGE_SIZE;
690                         count -= PAGE_SIZE; /* example had PAGE_SIZE here */
691                 }
692         } else {
693                 pdx->sgl[frameInfo][0].length = count;
694         }
695         pdx->sgEntries[frameInfo] =
696             usb_buffer_map_sg(pdx->udev, epAddr, pdx->sgl[frameInfo],
697                               pdx->maplist_numPagesMapped[frameInfo]);
698         dbg("number of sgEntries = %d", pdx->sgEntries[frameInfo]);
699         pdx->userBufMapped = 1;
700         vfree(maplist_p);
701
702         /* Create and Send the URB's for each s/g entry */
703         pdx->PixelUrb[frameInfo] =
704             kmalloc(pdx->sgEntries[frameInfo] * sizeof(struct urb *),
705                     GFP_KERNEL);
706         if (!pdx->PixelUrb[frameInfo]) {
707                 dbg("Can't Allocate Memory for Urb");
708                 return -ENOMEM;
709         }
710         for (i = 0; i < pdx->sgEntries[frameInfo]; i++) {
711                 /* 0 iso packets because we're using BULK transfers */
712                 pdx->PixelUrb[frameInfo][i] = usb_alloc_urb(0, GFP_KERNEL);
713                 usb_fill_bulk_urb(pdx->PixelUrb[frameInfo][i],
714                                   pdx->udev,
715                                   epAddr,
716                                   (dma_addr_t *) sg_dma_address(&pdx->
717                                                                 sgl[frameInfo]
718                                                                 [i]),
719                                   sg_dma_len(&pdx->sgl[frameInfo][i]),
720                                   piusb_readPIXEL_callback, (void *)pdx);
721                 pdx->PixelUrb[frameInfo][i]->transfer_dma =
722                     sg_dma_address(&pdx->sgl[frameInfo][i]);
723                 pdx->PixelUrb[frameInfo][i]->transfer_flags =
724                     URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
725         }
726         /* only interrupt when last URB completes */
727         pdx->PixelUrb[frameInfo][--i]->transfer_flags &= ~URB_NO_INTERRUPT;
728         pdx->pendedPixelUrbs[frameInfo] =
729             kmalloc((pdx->sgEntries[frameInfo] * sizeof(char)), GFP_KERNEL);
730         if (!pdx->pendedPixelUrbs[frameInfo])
731                 dbg("Can't allocate Memory for pendedPixelUrbs");
732         for (i = 0; i < pdx->sgEntries[frameInfo]; i++) {
733                 err = usb_submit_urb(pdx->PixelUrb[frameInfo][i], GFP_ATOMIC);
734                 if (err) {
735                         dbg("%s %d\n", "submit urb error =", err);
736                         pdx->pendedPixelUrbs[frameInfo][i] = 0;
737                         return err;
738                 }
739                 pdx->pendedPixelUrbs[frameInfo][i] = 1;
740         }
741         return 0;
742 }
743
744 static const struct file_operations piusb_fops = {
745         .owner = THIS_MODULE,
746         .ioctl = piusb_ioctl,
747         .open = piusb_open,
748         .release = piusb_release,
749 };
750
751 static struct usb_class_driver piusb_class = {
752         .name = "usb/rspiusb%d",
753         .fops = &piusb_fops,
754         .minor_base = PIUSB_MINOR_BASE,
755 };
756
757 /**
758  *      piusb_probe
759  *
760  *      Called by the usb core when a new device is connected that it thinks
761  *      this driver might be interested in.
762  */
763 static int piusb_probe(struct usb_interface *interface,
764                        const struct usb_device_id *id)
765 {
766         struct device_extension *pdx = NULL;
767         struct usb_host_interface *iface_desc;
768         struct usb_endpoint_descriptor *endpoint;
769         int i;
770         int retval = -ENOMEM;
771
772         dev_dbg(&interface->dev, "%s - Looking for PI USB Hardware", __func__);
773
774         pdx = kzalloc(sizeof(struct device_extension), GFP_KERNEL);
775         if (pdx == NULL) {
776                 dev_err(&interface->dev, "Out of memory\n");
777                 goto error;
778         }
779         kref_init(&pdx->kref);
780         pdx->udev = usb_get_dev(interface_to_usbdev(interface));
781         pdx->interface = interface;
782         iface_desc = interface->cur_altsetting;
783
784         /* See if the device offered us matches what we can accept */
785         if ((pdx->udev->descriptor.idVendor != VENDOR_ID)
786             || ((pdx->udev->descriptor.idProduct != PIXIS_PID)
787                 && (pdx->udev->descriptor.idProduct != ST133_PID)))
788                 return -ENODEV;
789
790         pdx->iama = pdx->udev->descriptor.idProduct;
791
792         if (debug) {
793                 if (pdx->udev->descriptor.idProduct == PIXIS_PID)
794                         dbg("PIUSB:Pixis Camera Found");
795                 else
796                         dbg("PIUSB:ST133 USB Controller Found");
797                 if (pdx->udev->speed == USB_SPEED_HIGH)
798                         dbg("Highspeed(USB2.0) Device Attached");
799                 else
800                         dbg("Lowspeed (USB1.1) Device Attached");
801
802                 dbg("NumEndpoints in Configuration: %d",
803                     iface_desc->desc.bNumEndpoints);
804         }
805         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
806                 endpoint = &iface_desc->endpoint[i].desc;
807                 if (debug) {
808                         dbg("Endpoint[%d]->bDescriptorType = %d", i,
809                             endpoint->bDescriptorType);
810                         dbg("Endpoint[%d]->bEndpointAddress = 0x%02X", i,
811                             endpoint->bEndpointAddress);
812                         dbg("Endpoint[%d]->bbmAttributes = %d", i,
813                             endpoint->bmAttributes);
814                         dbg("Endpoint[%d]->MaxPacketSize = %d\n", i,
815                             endpoint->wMaxPacketSize);
816                 }
817                 if (usb_endpoint_xfer_bulk(endpoint)) {
818                         if (usb_endpoint_dir_in(endpoint))
819                                 pdx->hEP[i] =
820                                     usb_rcvbulkpipe(pdx->udev,
821                                                     endpoint->bEndpointAddress);
822                         else
823                                 pdx->hEP[i] =
824                                     usb_sndbulkpipe(pdx->udev,
825                                                     endpoint->bEndpointAddress);
826                 }
827         }
828         usb_set_intfdata(interface, pdx);
829         retval = usb_register_dev(interface, &piusb_class);
830         if (retval) {
831                 err("Not able to get a minor for this device.");
832                 usb_set_intfdata(interface, NULL);
833                 goto error;
834         }
835         pdx->present = 1;
836
837         /* we can register the device now, as it is ready */
838         pdx->minor = interface->minor;
839         /* let the user know what node this device is now attached to */
840         dbg("PI USB2.0 device now attached to piusb-%d", pdx->minor);
841         return 0;
842
843 error:
844         if (pdx)
845                 kref_put(&pdx->kref, piusb_delete);
846         return retval;
847 }
848
849 /**
850  *      piusb_disconnect
851  *
852  *      Called by the usb core when the device is removed from the system.
853  *
854  *      This routine guarantees that the driver will not submit any more urbs
855  *      by clearing pdx->udev.  It is also supposed to terminate any currently
856  *      active urbs.  Unfortunately, usb_bulk_msg(), used in piusb_read(), does
857  *      not provide any way to do this.  But at least we can cancel an active
858  *      write.
859  */
860 static void piusb_disconnect(struct usb_interface *interface)
861 {
862         struct device_extension *pdx;
863         int minor = interface->minor;
864
865         lock_kernel();
866
867         pdx = usb_get_intfdata(interface);
868         usb_set_intfdata(interface, NULL);
869
870         /* give back our minor */
871         usb_deregister_dev(interface, &piusb_class);
872
873         unlock_kernel();
874
875         /* prevent device read, write and ioctl */
876         pdx->present = 0;
877         kref_put(&pdx->kref, piusb_delete);
878         dbg("PI USB2.0 device #%d now disconnected\n", minor);
879 }
880
881 static struct usb_driver piusb_driver = {
882         .name = "sub",
883         .probe = piusb_probe,
884         .disconnect = piusb_disconnect,
885         .id_table = pi_device_table,
886 };
887
888 /**
889  *      piusb_init
890  */
891 static int __init piusb_init(void)
892 {
893         int result;
894
895         lastErr = 0;
896         errCnt = 0;
897
898         /* register this driver with the USB subsystem */
899         result = usb_register(&piusb_driver);
900         if (result)
901                 printk(KERN_ERR KBUILD_MODNAME
902                                 ": usb_register failed. Error number %d\n",
903                                 result);
904         else
905                 printk(KERN_INFO KBUILD_MODNAME ":%s: %s\n", DRIVER_DESC,
906                                 DRIVER_VERSION);
907         return result;
908 }
909
910 /**
911  *      piusb_exit
912  */
913 static void __exit piusb_exit(void)
914 {
915         /* deregister this driver with the USB subsystem */
916         usb_deregister(&piusb_driver);
917 }
918
919 module_init(piusb_init);
920 module_exit(piusb_exit);
921
922 /* Module parameters */
923 module_param(debug, int, 0);
924 MODULE_PARM_DESC(debug, "Debug enabled or not");
925
926 MODULE_AUTHOR(DRIVER_AUTHOR);
927 MODULE_DESCRIPTION(DRIVER_DESC);
928 MODULE_LICENSE("GPL v2");