]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/udlfb/udlfb.c
staging: udlfb: remove metrics_misc sysfs attribute
[mv-sheeva.git] / drivers / staging / udlfb / udlfb.c
1 /*
2  * udlfb.c -- Framebuffer driver for DisplayLink USB controller
3  *
4  * Copyright (C) 2009 Roberto De Ioris <roberto@unbit.it>
5  * Copyright (C) 2009 Jaya Kumar <jayakumar.lkml@gmail.com>
6  * Copyright (C) 2009 Bernie Thompson <bernie@plugable.com>
7  *
8  * This file is subject to the terms and conditions of the GNU General Public
9  * License v2. See the file COPYING in the main directory of this archive for
10  * more details.
11  *
12  * Layout is based on skeletonfb by James Simmons and Geert Uytterhoeven,
13  * usb-skeleton by GregKH.
14  *
15  * Device-specific portions based on information from Displaylink, with work
16  * from Florian Echtler, Henrik Bjerregaard Pedersen, and others.
17  */
18
19 #include <linux/module.h>
20 #include <linux/kernel.h>
21 #include <linux/init.h>
22 #include <linux/usb.h>
23 #include <linux/uaccess.h>
24 #include <linux/mm.h>
25 #include <linux/fb.h>
26 #include <linux/vmalloc.h>
27 #include <linux/slab.h>
28
29 #include "udlfb.h"
30
31 static struct fb_fix_screeninfo dlfb_fix = {
32         .id =           "udlfb",
33         .type =         FB_TYPE_PACKED_PIXELS,
34         .visual =       FB_VISUAL_TRUECOLOR,
35         .xpanstep =     0,
36         .ypanstep =     0,
37         .ywrapstep =    0,
38         .accel =        FB_ACCEL_NONE,
39 };
40
41 static const u32 udlfb_info_flags = FBINFO_DEFAULT | FBINFO_READS_FAST |
42 #ifdef FBINFO_VIRTFB
43                 FBINFO_VIRTFB |
44 #endif
45                 FBINFO_HWACCEL_IMAGEBLIT | FBINFO_HWACCEL_FILLRECT |
46                 FBINFO_HWACCEL_COPYAREA | FBINFO_MISC_ALWAYS_SETPAR;
47
48 /*
49  * There are many DisplayLink-based products, all with unique PIDs. We are able
50  * to support all volume ones (circa 2009) with a single driver, so we match
51  * globally on VID. TODO: Probe() needs to detect when we might be running
52  * "future" chips, and bail on those, so a compatible driver can match.
53  */
54 static struct usb_device_id id_table[] = {
55         {.idVendor = 0x17e9, .match_flags = USB_DEVICE_ID_MATCH_VENDOR,},
56         {},
57 };
58 MODULE_DEVICE_TABLE(usb, id_table);
59
60 #ifndef CONFIG_FB_DEFERRED_IO
61 #warning Please set CONFIG_FB_DEFFERRED_IO option to support generic fbdev apps
62 #endif
63
64 #ifndef CONFIG_FB_SYS_IMAGEBLIT
65 #ifndef CONFIG_FB_SYS_IMAGEBLIT_MODULE
66 #warning Please set CONFIG_FB_SYS_IMAGEBLIT option to support fb console
67 #endif
68 #endif
69
70 #ifndef CONFIG_FB_MODE_HELPERS
71 #warning CONFIG_FB_MODE_HELPERS required. Expect build break
72 #endif
73
74 /* dlfb keeps a list of urbs for efficient bulk transfers */
75 static void dlfb_urb_completion(struct urb *urb);
76 static struct urb *dlfb_get_urb(struct dlfb_data *dev);
77 static int dlfb_submit_urb(struct dlfb_data *dev, struct urb * urb, size_t len);
78 static int dlfb_alloc_urb_list(struct dlfb_data *dev, int count, size_t size);
79 static void dlfb_free_urb_list(struct dlfb_data *dev);
80
81 /* other symbols with dependents */
82 #ifdef CONFIG_FB_DEFERRED_IO
83 static struct fb_deferred_io dlfb_defio;
84 #endif
85
86 /*
87  * All DisplayLink bulk operations start with 0xAF, followed by specific code
88  * All operations are written to buffers which then later get sent to device
89  */
90 static char *dlfb_set_register(char *buf, u8 reg, u8 val)
91 {
92         *buf++ = 0xAF;
93         *buf++ = 0x20;
94         *buf++ = reg;
95         *buf++ = val;
96         return buf;
97 }
98
99 static char *dlfb_vidreg_lock(char *buf)
100 {
101         return dlfb_set_register(buf, 0xFF, 0x00);
102 }
103
104 static char *dlfb_vidreg_unlock(char *buf)
105 {
106         return dlfb_set_register(buf, 0xFF, 0xFF);
107 }
108
109 /*
110  * On/Off for driving the DisplayLink framebuffer to the display
111  *  0x00 H and V sync on
112  *  0x01 H and V sync off (screen blank but powered)
113  *  0x07 DPMS powerdown (requires modeset to come back)
114  */
115 static char *dlfb_enable_hvsync(char *buf, bool enable)
116 {
117         if (enable)
118                 return dlfb_set_register(buf, 0x1F, 0x00);
119         else
120                 return dlfb_set_register(buf, 0x1F, 0x07);
121 }
122
123 static char *dlfb_set_color_depth(char *buf, u8 selection)
124 {
125         return dlfb_set_register(buf, 0x00, selection);
126 }
127
128 static char *dlfb_set_base16bpp(char *wrptr, u32 base)
129 {
130         /* the base pointer is 16 bits wide, 0x20 is hi byte. */
131         wrptr = dlfb_set_register(wrptr, 0x20, base >> 16);
132         wrptr = dlfb_set_register(wrptr, 0x21, base >> 8);
133         return dlfb_set_register(wrptr, 0x22, base);
134 }
135
136 /*
137  * DisplayLink HW has separate 16bpp and 8bpp framebuffers.
138  * In 24bpp modes, the low 323 RGB bits go in the 8bpp framebuffer
139  */
140 static char *dlfb_set_base8bpp(char *wrptr, u32 base)
141 {
142         wrptr = dlfb_set_register(wrptr, 0x26, base >> 16);
143         wrptr = dlfb_set_register(wrptr, 0x27, base >> 8);
144         return dlfb_set_register(wrptr, 0x28, base);
145 }
146
147 static char *dlfb_set_register_16(char *wrptr, u8 reg, u16 value)
148 {
149         wrptr = dlfb_set_register(wrptr, reg, value >> 8);
150         return dlfb_set_register(wrptr, reg+1, value);
151 }
152
153 /*
154  * This is kind of weird because the controller takes some
155  * register values in a different byte order than other registers.
156  */
157 static char *dlfb_set_register_16be(char *wrptr, u8 reg, u16 value)
158 {
159         wrptr = dlfb_set_register(wrptr, reg, value);
160         return dlfb_set_register(wrptr, reg+1, value >> 8);
161 }
162
163 /*
164  * LFSR is linear feedback shift register. The reason we have this is
165  * because the display controller needs to minimize the clock depth of
166  * various counters used in the display path. So this code reverses the
167  * provided value into the lfsr16 value by counting backwards to get
168  * the value that needs to be set in the hardware comparator to get the
169  * same actual count. This makes sense once you read above a couple of
170  * times and think about it from a hardware perspective.
171  */
172 static u16 dlfb_lfsr16(u16 actual_count)
173 {
174         u32 lv = 0xFFFF; /* This is the lfsr value that the hw starts with */
175
176         while (actual_count--) {
177                 lv =     ((lv << 1) |
178                         (((lv >> 15) ^ (lv >> 4) ^ (lv >> 2) ^ (lv >> 1)) & 1))
179                         & 0xFFFF;
180         }
181
182         return (u16) lv;
183 }
184
185 /*
186  * This does LFSR conversion on the value that is to be written.
187  * See LFSR explanation above for more detail.
188  */
189 static char *dlfb_set_register_lfsr16(char *wrptr, u8 reg, u16 value)
190 {
191         return dlfb_set_register_16(wrptr, reg, dlfb_lfsr16(value));
192 }
193
194 /*
195  * This takes a standard fbdev screeninfo struct and all of its monitor mode
196  * details and converts them into the DisplayLink equivalent register commands.
197  */
198 static char *dlfb_set_vid_cmds(char *wrptr, struct fb_var_screeninfo *var)
199 {
200         u16 xds, yds;
201         u16 xde, yde;
202         u16 yec;
203
204         /* x display start */
205         xds = var->left_margin + var->hsync_len;
206         wrptr = dlfb_set_register_lfsr16(wrptr, 0x01, xds);
207         /* x display end */
208         xde = xds + var->xres;
209         wrptr = dlfb_set_register_lfsr16(wrptr, 0x03, xde);
210
211         /* y display start */
212         yds = var->upper_margin + var->vsync_len;
213         wrptr = dlfb_set_register_lfsr16(wrptr, 0x05, yds);
214         /* y display end */
215         yde = yds + var->yres;
216         wrptr = dlfb_set_register_lfsr16(wrptr, 0x07, yde);
217
218         /* x end count is active + blanking - 1 */
219         wrptr = dlfb_set_register_lfsr16(wrptr, 0x09,
220                         xde + var->right_margin - 1);
221
222         /* libdlo hardcodes hsync start to 1 */
223         wrptr = dlfb_set_register_lfsr16(wrptr, 0x0B, 1);
224
225         /* hsync end is width of sync pulse + 1 */
226         wrptr = dlfb_set_register_lfsr16(wrptr, 0x0D, var->hsync_len + 1);
227
228         /* hpixels is active pixels */
229         wrptr = dlfb_set_register_16(wrptr, 0x0F, var->xres);
230
231         /* yendcount is vertical active + vertical blanking */
232         yec = var->yres + var->upper_margin + var->lower_margin +
233                         var->vsync_len;
234         wrptr = dlfb_set_register_lfsr16(wrptr, 0x11, yec);
235
236         /* libdlo hardcodes vsync start to 0 */
237         wrptr = dlfb_set_register_lfsr16(wrptr, 0x13, 0);
238
239         /* vsync end is width of vsync pulse */
240         wrptr = dlfb_set_register_lfsr16(wrptr, 0x15, var->vsync_len);
241
242         /* vpixels is active pixels */
243         wrptr = dlfb_set_register_16(wrptr, 0x17, var->yres);
244
245         /* convert picoseconds to 5kHz multiple for pclk5k = x * 1E12/5k */
246         wrptr = dlfb_set_register_16be(wrptr, 0x1B,
247                         200*1000*1000/var->pixclock);
248
249         return wrptr;
250 }
251
252 /*
253  * This takes a standard fbdev screeninfo struct that was fetched or prepared
254  * and then generates the appropriate command sequence that then drives the
255  * display controller.
256  */
257 static int dlfb_set_video_mode(struct dlfb_data *dev,
258                                 struct fb_var_screeninfo *var)
259 {
260         char *buf;
261         char *wrptr;
262         int retval = 0;
263         int writesize;
264         struct urb *urb;
265
266         if (!atomic_read(&dev->usb_active))
267                 return -EPERM;
268
269         urb = dlfb_get_urb(dev);
270         if (!urb)
271                 return -ENOMEM;
272         buf = (char *) urb->transfer_buffer;
273
274         /*
275         * This first section has to do with setting the base address on the
276         * controller * associated with the display. There are 2 base
277         * pointers, currently, we only * use the 16 bpp segment.
278         */
279         wrptr = dlfb_vidreg_lock(buf);
280         wrptr = dlfb_set_color_depth(wrptr, 0x00);
281         /* set base for 16bpp segment to 0 */
282         wrptr = dlfb_set_base16bpp(wrptr, 0);
283         /* set base for 8bpp segment to end of fb */
284         wrptr = dlfb_set_base8bpp(wrptr, dev->info->fix.smem_len);
285
286         wrptr = dlfb_set_vid_cmds(wrptr, var);
287         wrptr = dlfb_enable_hvsync(wrptr, true);
288         wrptr = dlfb_vidreg_unlock(wrptr);
289
290         writesize = wrptr - buf;
291
292         retval = dlfb_submit_urb(dev, urb, writesize);
293
294         return retval;
295 }
296
297 static int dlfb_ops_mmap(struct fb_info *info, struct vm_area_struct *vma)
298 {
299         unsigned long start = vma->vm_start;
300         unsigned long size = vma->vm_end - vma->vm_start;
301         unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
302         unsigned long page, pos;
303         struct dlfb_data *dev = info->par;
304
305         dl_notice("MMAP: %lu %u\n", offset + size, info->fix.smem_len);
306
307         if (offset + size > info->fix.smem_len)
308                 return -EINVAL;
309
310         pos = (unsigned long)info->fix.smem_start + offset;
311
312         while (size > 0) {
313                 page = vmalloc_to_pfn((void *)pos);
314                 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
315                         return -EAGAIN;
316
317                 start += PAGE_SIZE;
318                 pos += PAGE_SIZE;
319                 if (size > PAGE_SIZE)
320                         size -= PAGE_SIZE;
321                 else
322                         size = 0;
323         }
324
325         vma->vm_flags |= VM_RESERVED;   /* avoid to swap out this VMA */
326         return 0;
327
328 }
329
330 /*
331  * Trims identical data from front and back of line
332  * Sets new front buffer address and width
333  * And returns byte count of identical pixels
334  * Assumes CPU natural alignment (unsigned long)
335  * for back and front buffer ptrs and width
336  */
337 static int dlfb_trim_hline(const u8 *bback, const u8 **bfront, int *width_bytes)
338 {
339         int j, k;
340         const unsigned long *back = (const unsigned long *) bback;
341         const unsigned long *front = (const unsigned long *) *bfront;
342         const int width = *width_bytes / sizeof(unsigned long);
343         int identical = width;
344         int start = width;
345         int end = width;
346
347         prefetch((void *) front);
348         prefetch((void *) back);
349
350         for (j = 0; j < width; j++) {
351                 if (back[j] != front[j]) {
352                         start = j;
353                         break;
354                 }
355         }
356
357         for (k = width - 1; k > j; k--) {
358                 if (back[k] != front[k]) {
359                         end = k+1;
360                         break;
361                 }
362         }
363
364         identical = start + (width - end);
365         *bfront = (u8 *) &front[start];
366         *width_bytes = (end - start) * sizeof(unsigned long);
367
368         return identical * sizeof(unsigned long);
369 }
370
371 /*
372  * Render a command stream for an encoded horizontal line segment of pixels.
373  *
374  * A command buffer holds several commands.
375  * It always begins with a fresh command header
376  * (the protocol doesn't require this, but we enforce it to allow
377  * multiple buffers to be potentially encoded and sent in parallel).
378  * A single command encodes one contiguous horizontal line of pixels
379  *
380  * The function relies on the client to do all allocation, so that
381  * rendering can be done directly to output buffers (e.g. USB URBs).
382  * The function fills the supplied command buffer, providing information
383  * on where it left off, so the client may call in again with additional
384  * buffers if the line will take several buffers to complete.
385  *
386  * A single command can transmit a maximum of 256 pixels,
387  * regardless of the compression ratio (protocol design limit).
388  * To the hardware, 0 for a size byte means 256
389  * 
390  * Rather than 256 pixel commands which are either rl or raw encoded,
391  * the rlx command simply assumes alternating raw and rl spans within one cmd.
392  * This has a slightly larger header overhead, but produces more even results.
393  * It also processes all data (read and write) in a single pass.
394  * Performance benchmarks of common cases show it having just slightly better
395  * compression than 256 pixel raw -or- rle commands, with similar CPU consumpion.
396  * But for very rl friendly data, will compress not quite as well.
397  */
398 static void dlfb_compress_hline(
399         const uint16_t **pixel_start_ptr,
400         const uint16_t *const pixel_end,
401         uint32_t *device_address_ptr,
402         uint8_t **command_buffer_ptr,
403         const uint8_t *const cmd_buffer_end)
404 {
405         const uint16_t *pixel = *pixel_start_ptr;
406         uint32_t dev_addr  = *device_address_ptr;
407         uint8_t *cmd = *command_buffer_ptr;
408         const int bpp = 2;
409
410         while ((pixel_end > pixel) &&
411                (cmd_buffer_end - MIN_RLX_CMD_BYTES > cmd)) {
412                 uint8_t *raw_pixels_count_byte = 0;
413                 uint8_t *cmd_pixels_count_byte = 0;
414                 const uint16_t *raw_pixel_start = 0;
415                 const uint16_t *cmd_pixel_start, *cmd_pixel_end = 0;
416                 const uint32_t be_dev_addr = cpu_to_be32(dev_addr);
417
418                 prefetchw((void *) cmd); /* pull in one cache line at least */
419
420                 *cmd++ = 0xAF;
421                 *cmd++ = 0x6B;
422                 *cmd++ = (uint8_t) ((be_dev_addr >> 8) & 0xFF);
423                 *cmd++ = (uint8_t) ((be_dev_addr >> 16) & 0xFF);
424                 *cmd++ = (uint8_t) ((be_dev_addr >> 24) & 0xFF);
425
426                 cmd_pixels_count_byte = cmd++; /*  we'll know this later */
427                 cmd_pixel_start = pixel;
428
429                 raw_pixels_count_byte = cmd++; /*  we'll know this later */
430                 raw_pixel_start = pixel;
431
432                 cmd_pixel_end = pixel + min(MAX_CMD_PIXELS + 1,
433                         min((int)(pixel_end - pixel),
434                             (int)(cmd_buffer_end - cmd) / bpp));
435
436                 prefetch_range((void *) pixel, (cmd_pixel_end - pixel) * bpp);
437
438                 while (pixel < cmd_pixel_end) {
439                         const uint16_t * const repeating_pixel = pixel;
440
441                         *(uint16_t *)cmd = cpu_to_be16p(pixel);
442                         cmd += 2;
443                         pixel++;
444
445                         if (unlikely((pixel < cmd_pixel_end) &&
446                                      (*pixel == *repeating_pixel))) {
447                                 /* go back and fill in raw pixel count */
448                                 *raw_pixels_count_byte = ((repeating_pixel -
449                                                 raw_pixel_start) + 1) & 0xFF;
450
451                                 while ((pixel < cmd_pixel_end)
452                                        && (*pixel == *repeating_pixel)) {
453                                         pixel++;
454                                 }
455
456                                 /* immediately after raw data is repeat byte */
457                                 *cmd++ = ((pixel - repeating_pixel) - 1) & 0xFF;
458
459                                 /* Then start another raw pixel span */
460                                 raw_pixel_start = pixel;
461                                 raw_pixels_count_byte = cmd++;
462                         }
463                 }
464
465                 if (pixel > raw_pixel_start) {
466                         /* finalize last RAW span */
467                         *raw_pixels_count_byte = (pixel-raw_pixel_start) & 0xFF;
468                 }
469
470                 *cmd_pixels_count_byte = (pixel - cmd_pixel_start) & 0xFF;
471                 dev_addr += (pixel - cmd_pixel_start) * bpp;
472         }
473
474         if (cmd_buffer_end <= MIN_RLX_CMD_BYTES + cmd) {
475                 /* Fill leftover bytes with no-ops */
476                 if (cmd_buffer_end > cmd)
477                         memset(cmd, 0xAF, cmd_buffer_end - cmd);
478                 cmd = (uint8_t *) cmd_buffer_end;
479         }
480
481         *command_buffer_ptr = cmd;
482         *pixel_start_ptr = pixel;
483         *device_address_ptr = dev_addr;
484
485         return;
486 }
487
488 /*
489  * There are 3 copies of every pixel: The front buffer that the fbdev
490  * client renders to, the actual framebuffer across the USB bus in hardware
491  * (that we can only write to, slowly, and can never read), and (optionally)
492  * our shadow copy that tracks what's been sent to that hardware buffer.
493  */
494 static void dlfb_render_hline(struct dlfb_data *dev, struct urb **urb_ptr,
495                               const char *front, char **urb_buf_ptr,
496                               u32 byte_offset, u32 byte_width,
497                               int *ident_ptr, int *sent_ptr)
498 {
499         const u8 *line_start, *line_end, *next_pixel;
500         u32 dev_addr = dev->base16 + byte_offset;
501         struct urb *urb = *urb_ptr;
502         u8 *cmd = *urb_buf_ptr;
503         u8 *cmd_end = (u8 *) urb->transfer_buffer + urb->transfer_buffer_length;
504
505         line_start = (u8 *) (front + byte_offset);
506         next_pixel = line_start;
507         line_end = next_pixel + byte_width;
508
509         if (dev->backing_buffer) {
510                 int offset;
511                 const u8 *back_start = (u8 *) (dev->backing_buffer
512                                                 + byte_offset);
513
514                 *ident_ptr += dlfb_trim_hline(back_start, &next_pixel,
515                         &byte_width);
516
517                 offset = next_pixel - line_start;
518                 line_end = next_pixel + byte_width;
519                 dev_addr += offset;
520                 back_start += offset;
521                 line_start += offset;
522
523                 memcpy((char *)back_start, (char *) line_start,
524                        byte_width);
525         }
526
527         while (next_pixel < line_end) {
528
529                 dlfb_compress_hline((const uint16_t **) &next_pixel,
530                              (const uint16_t *) line_end, &dev_addr,
531                         (u8 **) &cmd, (u8 *) cmd_end);
532
533                 if (cmd >= cmd_end) {
534                         int len = cmd - (u8 *) urb->transfer_buffer;
535                         if (dlfb_submit_urb(dev, urb, len))
536                                 return; /* lost pixels is set */
537                         *sent_ptr += len;
538                         urb = dlfb_get_urb(dev);
539                         if (!urb)
540                                 return; /* lost_pixels is set */
541                         *urb_ptr = urb;
542                         cmd = urb->transfer_buffer;
543                         cmd_end = &cmd[urb->transfer_buffer_length];
544                 }
545         }
546
547         *urb_buf_ptr = cmd;
548 }
549
550 int dlfb_handle_damage(struct dlfb_data *dev, int x, int y,
551                int width, int height, char *data)
552 {
553         int i, ret;
554         char *cmd;
555         cycles_t start_cycles, end_cycles;
556         int bytes_sent = 0;
557         int bytes_identical = 0;
558         struct urb *urb;
559         int aligned_x;
560
561         start_cycles = get_cycles();
562
563         aligned_x = DL_ALIGN_DOWN(x, sizeof(unsigned long));
564         width = DL_ALIGN_UP(width + (x-aligned_x), sizeof(unsigned long));
565         x = aligned_x;
566
567         if ((width <= 0) ||
568             (x + width > dev->info->var.xres) ||
569             (y + height > dev->info->var.yres))
570                 return -EINVAL;
571
572         if (!atomic_read(&dev->usb_active))
573                 return 0;
574
575         urb = dlfb_get_urb(dev);
576         if (!urb)
577                 return 0;
578         cmd = urb->transfer_buffer;
579
580         for (i = y; i < y + height ; i++) {
581                 const int line_offset = dev->info->fix.line_length * i;
582                 const int byte_offset = line_offset + (x * BPP);
583
584                 dlfb_render_hline(dev, &urb, (char *) dev->info->fix.smem_start,
585                                   &cmd, byte_offset, width * BPP,
586                                   &bytes_identical, &bytes_sent);
587         }
588
589         if (cmd > (char *) urb->transfer_buffer) {
590                 /* Send partial buffer remaining before exiting */
591                 int len = cmd - (char *) urb->transfer_buffer;
592                 ret = dlfb_submit_urb(dev, urb, len);
593                 bytes_sent += len;
594         } else
595                 dlfb_urb_completion(urb);
596
597         atomic_add(bytes_sent, &dev->bytes_sent);
598         atomic_add(bytes_identical, &dev->bytes_identical);
599         atomic_add(width*height*2, &dev->bytes_rendered);
600         end_cycles = get_cycles();
601         atomic_add(((unsigned int) ((end_cycles - start_cycles)
602                     >> 10)), /* Kcycles */
603                    &dev->cpu_kcycles_used);
604
605         return 0;
606 }
607
608 static ssize_t dlfb_ops_read(struct fb_info *info, char __user *buf,
609                          size_t count, loff_t *ppos)
610 {
611         ssize_t result = -ENOSYS;
612
613 #if defined CONFIG_FB_SYS_FOPS || defined CONFIG_FB_SYS_FOPS_MODULE
614         result = fb_sys_read(info, buf, count, ppos);
615 #endif
616
617         return result;
618 }
619
620 /*
621  * Path triggered by usermode clients who write to filesystem
622  * e.g. cat filename > /dev/fb1
623  * Not used by X Windows or text-mode console. But useful for testing.
624  * Slow because of extra copy and we must assume all pixels dirty.
625  */
626 static ssize_t dlfb_ops_write(struct fb_info *info, const char __user *buf,
627                           size_t count, loff_t *ppos)
628 {
629         ssize_t result = -ENOSYS;
630         struct dlfb_data *dev = info->par;
631         u32 offset = (u32) *ppos;
632
633 #if defined CONFIG_FB_SYS_FOPS || defined CONFIG_FB_SYS_FOPS_MODULE
634
635         result = fb_sys_write(info, buf, count, ppos);
636
637         if (result > 0) {
638                 int start = max((int)(offset / info->fix.line_length) - 1, 0);
639                 int lines = min((u32)((result / info->fix.line_length) + 1),
640                                 (u32)info->var.yres);
641
642                 dlfb_handle_damage(dev, 0, start, info->var.xres,
643                         lines, info->screen_base);
644         }
645 #endif
646
647         return result;
648 }
649
650 /* hardware has native COPY command (see libdlo), but not worth it for fbcon */
651 static void dlfb_ops_copyarea(struct fb_info *info,
652                                 const struct fb_copyarea *area)
653 {
654
655         struct dlfb_data *dev = info->par;
656
657 #if defined CONFIG_FB_SYS_COPYAREA || defined CONFIG_FB_SYS_COPYAREA_MODULE
658
659         sys_copyarea(info, area);
660
661         dlfb_handle_damage(dev, area->dx, area->dy,
662                         area->width, area->height, info->screen_base);
663 #endif
664
665 }
666
667 static void dlfb_ops_imageblit(struct fb_info *info,
668                                 const struct fb_image *image)
669 {
670         struct dlfb_data *dev = info->par;
671
672 #if defined CONFIG_FB_SYS_IMAGEBLIT || defined CONFIG_FB_SYS_IMAGEBLIT_MODULE
673
674         sys_imageblit(info, image);
675
676         dlfb_handle_damage(dev, image->dx, image->dy,
677                         image->width, image->height, info->screen_base);
678
679 #endif
680
681 }
682
683 static void dlfb_ops_fillrect(struct fb_info *info,
684                           const struct fb_fillrect *rect)
685 {
686         struct dlfb_data *dev = info->par;
687
688 #if defined CONFIG_FB_SYS_FILLRECT || defined CONFIG_FB_SYS_FILLRECT_MODULE
689
690         sys_fillrect(info, rect);
691
692         dlfb_handle_damage(dev, rect->dx, rect->dy, rect->width,
693                               rect->height, info->screen_base);
694 #endif
695
696 }
697
698 static void dlfb_get_edid(struct dlfb_data *dev)
699 {
700         int i;
701         int ret;
702         char rbuf[2];
703
704         for (i = 0; i < sizeof(dev->edid); i++) {
705                 ret = usb_control_msg(dev->udev,
706                                     usb_rcvctrlpipe(dev->udev, 0), (0x02),
707                                     (0x80 | (0x02 << 5)), i << 8, 0xA1, rbuf, 2,
708                                     0);
709                 dev->edid[i] = rbuf[1];
710         }
711 }
712
713 static int dlfb_ops_ioctl(struct fb_info *info, unsigned int cmd,
714                                 unsigned long arg)
715 {
716
717         struct dlfb_data *dev = info->par;
718         struct dloarea *area = NULL;
719
720         if (!atomic_read(&dev->usb_active))
721                 return 0;
722
723         /* TODO: Update X server to get this from sysfs instead */
724         if (cmd == DLFB_IOCTL_RETURN_EDID) {
725                 char *edid = (char *)arg;
726                 dlfb_get_edid(dev);
727                 if (copy_to_user(edid, dev->edid, sizeof(dev->edid)))
728                         return -EFAULT;
729                 return 0;
730         }
731
732         /* TODO: Help propose a standard fb.h ioctl to report mmap damage */
733         if (cmd == DLFB_IOCTL_REPORT_DAMAGE) {
734
735                 area = (struct dloarea *)arg;
736
737                 if (area->x < 0)
738                         area->x = 0;
739
740                 if (area->x > info->var.xres)
741                         area->x = info->var.xres;
742
743                 if (area->y < 0)
744                         area->y = 0;
745
746                 if (area->y > info->var.yres)
747                         area->y = info->var.yres;
748
749                 atomic_set(&dev->use_defio, 0);
750
751                 dlfb_handle_damage(dev, area->x, area->y, area->w, area->h,
752                            info->screen_base);
753         }
754
755         return 0;
756 }
757
758 /* taken from vesafb */
759 static int
760 dlfb_ops_setcolreg(unsigned regno, unsigned red, unsigned green,
761                unsigned blue, unsigned transp, struct fb_info *info)
762 {
763         int err = 0;
764
765         if (regno >= info->cmap.len)
766                 return 1;
767
768         if (regno < 16) {
769                 if (info->var.red.offset == 10) {
770                         /* 1:5:5:5 */
771                         ((u32 *) (info->pseudo_palette))[regno] =
772                             ((red & 0xf800) >> 1) |
773                             ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11);
774                 } else {
775                         /* 0:5:6:5 */
776                         ((u32 *) (info->pseudo_palette))[regno] =
777                             ((red & 0xf800)) |
778                             ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11);
779                 }
780         }
781
782         return err;
783 }
784
785 /*
786  * It's common for several clients to have framebuffer open simultaneously.
787  * e.g. both fbcon and X. Makes things interesting.
788  */
789 static int dlfb_ops_open(struct fb_info *info, int user)
790 {
791         struct dlfb_data *dev = info->par;
792
793 /*      if (user == 0)
794  *              We could special case kernel mode clients (fbcon) here
795  */
796
797         mutex_lock(&dev->fb_open_lock);
798
799         dev->fb_count++;
800
801 #ifdef CONFIG_FB_DEFERRED_IO
802         if ((atomic_read(&dev->use_defio)) && (info->fbdefio == NULL)) {
803                 /* enable defio */
804                 info->fbdefio = &dlfb_defio;
805                 fb_deferred_io_init(info);
806         }
807 #endif
808
809         dl_notice("open /dev/fb%d user=%d fb_info=%p count=%d\n",
810             info->node, user, info, dev->fb_count);
811
812         mutex_unlock(&dev->fb_open_lock);
813
814         return 0;
815 }
816
817 static int dlfb_ops_release(struct fb_info *info, int user)
818 {
819         struct dlfb_data *dev = info->par;
820
821         mutex_lock(&dev->fb_open_lock);
822
823         dev->fb_count--;
824
825 #ifdef CONFIG_FB_DEFERRED_IO
826         if ((dev->fb_count == 0) && (info->fbdefio)) {
827                 fb_deferred_io_cleanup(info);
828                 info->fbdefio = NULL;
829                 info->fbops->fb_mmap = dlfb_ops_mmap;
830         }
831 #endif
832
833         dl_notice("release /dev/fb%d user=%d count=%d\n",
834                   info->node, user, dev->fb_count);
835
836         mutex_unlock(&dev->fb_open_lock);
837
838         return 0;
839 }
840
841 /*
842  * Called when all client interfaces to start transactions have been disabled,
843  * and all references to our device instance (dlfb_data) are released.
844  * Every transaction must have a reference, so we know are fully spun down
845  */
846 static void dlfb_delete(struct kref *kref)
847 {
848         struct dlfb_data *dev = container_of(kref, struct dlfb_data, kref);
849
850         if (dev->backing_buffer)
851                 vfree(dev->backing_buffer);
852
853         mutex_destroy(&dev->fb_open_lock);
854
855         kfree(dev);
856 }
857
858 /*
859  * Called by fbdev as last part of unregister_framebuffer() process
860  * No new clients can open connections. Deallocate everything fb_info.
861  */
862 static void dlfb_ops_destroy(struct fb_info *info)
863 {
864         struct dlfb_data *dev = info->par;
865
866         if (info->cmap.len != 0)
867                 fb_dealloc_cmap(&info->cmap);
868         if (info->monspecs.modedb)
869                 fb_destroy_modedb(info->monspecs.modedb);
870         if (info->screen_base)
871                 vfree(info->screen_base);
872
873         fb_destroy_modelist(&info->modelist);
874
875         framebuffer_release(info);
876
877         /* ref taken before register_framebuffer() for dlfb_data clients */
878         kref_put(&dev->kref, dlfb_delete);
879 }
880
881 /*
882  * Check whether a video mode is supported by the DisplayLink chip
883  * We start from monitor's modes, so don't need to filter that here
884  */
885 static int dlfb_is_valid_mode(struct fb_videomode *mode,
886                 struct fb_info *info)
887 {
888         struct dlfb_data *dev = info->par;
889
890         if (mode->xres * mode->yres > dev->sku_pixel_limit)
891                 return 0;
892
893         return 1;
894 }
895
896 static void dlfb_var_color_format(struct fb_var_screeninfo *var)
897 {
898         const struct fb_bitfield red = { 11, 5, 0 };
899         const struct fb_bitfield green = { 5, 6, 0 };
900         const struct fb_bitfield blue = { 0, 5, 0 };
901
902         var->bits_per_pixel = 16;
903         var->red = red;
904         var->green = green;
905         var->blue = blue;
906 }
907
908 static int dlfb_ops_check_var(struct fb_var_screeninfo *var,
909                                 struct fb_info *info)
910 {
911         struct fb_videomode mode;
912
913         /* TODO: support dynamically changing framebuffer size */
914         if ((var->xres * var->yres * 2) > info->fix.smem_len)
915                 return -EINVAL;
916
917         /* set device-specific elements of var unrelated to mode */
918         dlfb_var_color_format(var);
919
920         fb_var_to_videomode(&mode, var);
921
922         if (!dlfb_is_valid_mode(&mode, info))
923                 return -EINVAL;
924
925         return 0;
926 }
927
928 static int dlfb_ops_set_par(struct fb_info *info)
929 {
930         struct dlfb_data *dev = info->par;
931
932         dl_notice("set_par mode %dx%d\n", info->var.xres, info->var.yres);
933
934         return dlfb_set_video_mode(dev, &info->var);
935 }
936
937 /*
938  * In order to come back from full DPMS off, we need to set the mode again
939  */
940 static int dlfb_ops_blank(int blank_mode, struct fb_info *info)
941 {
942         struct dlfb_data *dev = info->par;
943
944         if (blank_mode != FB_BLANK_UNBLANK) {
945                 char *bufptr;
946                 struct urb *urb;
947
948                 urb = dlfb_get_urb(dev);
949                 if (!urb)
950                         return 0;
951
952                 bufptr = (char *) urb->transfer_buffer;
953                 bufptr = dlfb_vidreg_lock(bufptr);
954                 bufptr = dlfb_enable_hvsync(bufptr, false);
955                 bufptr = dlfb_vidreg_unlock(bufptr);
956
957                 dlfb_submit_urb(dev, urb, bufptr -
958                                 (char *) urb->transfer_buffer);
959         } else {
960                 dlfb_set_video_mode(dev, &info->var);
961         }
962
963         return 0;
964 }
965
966 static struct fb_ops dlfb_ops = {
967         .owner = THIS_MODULE,
968         .fb_read = dlfb_ops_read,
969         .fb_write = dlfb_ops_write,
970         .fb_setcolreg = dlfb_ops_setcolreg,
971         .fb_fillrect = dlfb_ops_fillrect,
972         .fb_copyarea = dlfb_ops_copyarea,
973         .fb_imageblit = dlfb_ops_imageblit,
974         .fb_mmap = dlfb_ops_mmap,
975         .fb_ioctl = dlfb_ops_ioctl,
976         .fb_open = dlfb_ops_open,
977         .fb_release = dlfb_ops_release,
978         .fb_blank = dlfb_ops_blank,
979         .fb_check_var = dlfb_ops_check_var,
980         .fb_set_par = dlfb_ops_set_par,
981 };
982
983 /*
984  * Calls dlfb_get_edid() to query the EDID of attached monitor via usb cmds
985  * Then parses EDID into three places used by various parts of fbdev:
986  * fb_var_screeninfo contains the timing of the monitor's preferred mode
987  * fb_info.monspecs is full parsed EDID info, including monspecs.modedb
988  * fb_info.modelist is a linked list of all monitor & VESA modes which work
989  *
990  * If EDID is not readable/valid, then modelist is all VESA modes,
991  * monspecs is NULL, and fb_var_screeninfo is set to safe VESA mode
992  * Returns 0 if EDID parses successfully
993  */
994 static int dlfb_parse_edid(struct dlfb_data *dev,
995                             struct fb_var_screeninfo *var,
996                             struct fb_info *info)
997 {
998         int i;
999         const struct fb_videomode *default_vmode = NULL;
1000         int result = 0;
1001
1002         fb_destroy_modelist(&info->modelist);
1003         memset(&info->monspecs, 0, sizeof(info->monspecs));
1004
1005         dlfb_get_edid(dev);
1006         fb_edid_to_monspecs(dev->edid, &info->monspecs);
1007
1008         if (info->monspecs.modedb_len > 0) {
1009
1010                 for (i = 0; i < info->monspecs.modedb_len; i++) {
1011                         if (dlfb_is_valid_mode(&info->monspecs.modedb[i], info))
1012                                 fb_add_videomode(&info->monspecs.modedb[i],
1013                                         &info->modelist);
1014                 }
1015
1016                 default_vmode = fb_find_best_display(&info->monspecs,
1017                                                      &info->modelist);
1018         } else {
1019                 struct fb_videomode fb_vmode = {0};
1020
1021                 dl_err("Unable to get valid EDID from device/display\n");
1022                 result = 1;
1023
1024                 /*
1025                  * Add the standard VESA modes to our modelist
1026                  * Since we don't have EDID, there may be modes that
1027                  * overspec monitor and/or are incorrect aspect ratio, etc.
1028                  * But at least the user has a chance to choose
1029                  */
1030                 for (i = 0; i < VESA_MODEDB_SIZE; i++) {
1031                         if (dlfb_is_valid_mode((struct fb_videomode *)
1032                                                 &vesa_modes[i], info))
1033                                 fb_add_videomode(&vesa_modes[i],
1034                                                  &info->modelist);
1035                 }
1036
1037                 /*
1038                  * default to resolution safe for projectors
1039                  * (since they are most common case without EDID)
1040                  */
1041                 fb_vmode.xres = 800;
1042                 fb_vmode.yres = 600;
1043                 fb_vmode.refresh = 60;
1044                 default_vmode = fb_find_nearest_mode(&fb_vmode,
1045                                                      &info->modelist);
1046         }
1047
1048         fb_videomode_to_var(var, default_vmode);
1049         dlfb_var_color_format(var);
1050
1051         return result;
1052 }
1053
1054 static ssize_t metrics_bytes_rendered_show(struct device *fbdev,
1055                                    struct device_attribute *a, char *buf) {
1056         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1057         struct dlfb_data *dev = fb_info->par;
1058         return snprintf(buf, PAGE_SIZE, "%u\n",
1059                         atomic_read(&dev->bytes_rendered));
1060 }
1061
1062 static ssize_t metrics_bytes_identical_show(struct device *fbdev,
1063                                    struct device_attribute *a, char *buf) {
1064         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1065         struct dlfb_data *dev = fb_info->par;
1066         return snprintf(buf, PAGE_SIZE, "%u\n",
1067                         atomic_read(&dev->bytes_identical));
1068 }
1069
1070 static ssize_t metrics_bytes_sent_show(struct device *fbdev,
1071                                    struct device_attribute *a, char *buf) {
1072         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1073         struct dlfb_data *dev = fb_info->par;
1074         return snprintf(buf, PAGE_SIZE, "%u\n",
1075                         atomic_read(&dev->bytes_sent));
1076 }
1077
1078 static ssize_t metrics_cpu_kcycles_used_show(struct device *fbdev,
1079                                    struct device_attribute *a, char *buf) {
1080         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1081         struct dlfb_data *dev = fb_info->par;
1082         return snprintf(buf, PAGE_SIZE, "%u\n",
1083                         atomic_read(&dev->cpu_kcycles_used));
1084 }
1085
1086 static ssize_t edid_show(struct file *filp, struct kobject *kobj,
1087                          struct bin_attribute *a,
1088                          char *buf, loff_t off, size_t count) {
1089         struct device *fbdev = container_of(kobj, struct device, kobj);
1090         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1091         struct dlfb_data *dev = fb_info->par;
1092         char *edid = &dev->edid[0];
1093         const size_t size = sizeof(dev->edid);
1094
1095         if (dlfb_parse_edid(dev, &fb_info->var, fb_info))
1096                 return 0;
1097
1098         if (off >= size)
1099                 return 0;
1100
1101         if (off + count > size)
1102                 count = size - off;
1103         memcpy(buf, edid + off, count);
1104
1105         return count;
1106 }
1107
1108
1109 static ssize_t metrics_reset_store(struct device *fbdev,
1110                            struct device_attribute *attr,
1111                            const char *buf, size_t count)
1112 {
1113         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1114         struct dlfb_data *dev = fb_info->par;
1115
1116         atomic_set(&dev->bytes_rendered, 0);
1117         atomic_set(&dev->bytes_identical, 0);
1118         atomic_set(&dev->bytes_sent, 0);
1119         atomic_set(&dev->cpu_kcycles_used, 0);
1120
1121         return count;
1122 }
1123
1124 static ssize_t use_defio_show(struct device *fbdev,
1125                                    struct device_attribute *a, char *buf) {
1126         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1127         struct dlfb_data *dev = fb_info->par;
1128         return snprintf(buf, PAGE_SIZE, "%d\n",
1129                         atomic_read(&dev->use_defio));
1130 }
1131
1132 static ssize_t use_defio_store(struct device *fbdev,
1133                            struct device_attribute *attr,
1134                            const char *buf, size_t count)
1135 {
1136         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1137         struct dlfb_data *dev = fb_info->par;
1138
1139         if (count > 0) {
1140                 if (buf[0] == '0')
1141                         atomic_set(&dev->use_defio, 0);
1142                 if (buf[0] == '1')
1143                         atomic_set(&dev->use_defio, 1);
1144         }
1145         return count;
1146 }
1147
1148 static struct bin_attribute edid_attr = {
1149         .attr.name = "edid",
1150         .attr.mode = 0444,
1151         .size = 128,
1152         .read = edid_show,
1153 };
1154
1155 static struct device_attribute fb_device_attrs[] = {
1156         __ATTR_RO(metrics_bytes_rendered),
1157         __ATTR_RO(metrics_bytes_identical),
1158         __ATTR_RO(metrics_bytes_sent),
1159         __ATTR_RO(metrics_cpu_kcycles_used),
1160         __ATTR(metrics_reset, S_IWUGO, NULL, metrics_reset_store),
1161         __ATTR_RW(use_defio),
1162 };
1163
1164 #ifdef CONFIG_FB_DEFERRED_IO
1165 static void dlfb_dpy_deferred_io(struct fb_info *info,
1166                                 struct list_head *pagelist)
1167 {
1168         struct page *cur;
1169         struct fb_deferred_io *fbdefio = info->fbdefio;
1170         struct dlfb_data *dev = info->par;
1171         struct urb *urb;
1172         char *cmd;
1173         cycles_t start_cycles, end_cycles;
1174         int bytes_sent = 0;
1175         int bytes_identical = 0;
1176         int bytes_rendered = 0;
1177
1178         if (!atomic_read(&dev->use_defio))
1179                 return;
1180
1181         if (!atomic_read(&dev->usb_active))
1182                 return;
1183
1184         start_cycles = get_cycles();
1185
1186         urb = dlfb_get_urb(dev);
1187         if (!urb)
1188                 return;
1189         cmd = urb->transfer_buffer;
1190
1191         /* walk the written page list and render each to device */
1192         list_for_each_entry(cur, &fbdefio->pagelist, lru) {
1193                 dlfb_render_hline(dev, &urb, (char *) info->fix.smem_start,
1194                                   &cmd, cur->index << PAGE_SHIFT,
1195                                   PAGE_SIZE, &bytes_identical, &bytes_sent);
1196                 bytes_rendered += PAGE_SIZE;
1197         }
1198
1199         if (cmd > (char *) urb->transfer_buffer) {
1200                 /* Send partial buffer remaining before exiting */
1201                 int len = cmd - (char *) urb->transfer_buffer;
1202                 dlfb_submit_urb(dev, urb, len);
1203                 bytes_sent += len;
1204         } else
1205                 dlfb_urb_completion(urb);
1206
1207         atomic_add(bytes_sent, &dev->bytes_sent);
1208         atomic_add(bytes_identical, &dev->bytes_identical);
1209         atomic_add(bytes_rendered, &dev->bytes_rendered);
1210         end_cycles = get_cycles();
1211         atomic_add(((unsigned int) ((end_cycles - start_cycles)
1212                     >> 10)), /* Kcycles */
1213                    &dev->cpu_kcycles_used);
1214 }
1215
1216 static struct fb_deferred_io dlfb_defio = {
1217         .delay          = 5,
1218         .deferred_io    = dlfb_dpy_deferred_io,
1219 };
1220
1221 #endif
1222
1223 /*
1224  * This is necessary before we can communicate with the display controller.
1225  */
1226 static int dlfb_select_std_channel(struct dlfb_data *dev)
1227 {
1228         int ret;
1229         u8 set_def_chn[] = {       0x57, 0xCD, 0xDC, 0xA7,
1230                                 0x1C, 0x88, 0x5E, 0x15,
1231                                 0x60, 0xFE, 0xC6, 0x97,
1232                                 0x16, 0x3D, 0x47, 0xF2  };
1233
1234         ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
1235                         NR_USB_REQUEST_CHANNEL,
1236                         (USB_DIR_OUT | USB_TYPE_VENDOR), 0, 0,
1237                         set_def_chn, sizeof(set_def_chn), USB_CTRL_SET_TIMEOUT);
1238         return ret;
1239 }
1240
1241
1242 static int dlfb_usb_probe(struct usb_interface *interface,
1243                         const struct usb_device_id *id)
1244 {
1245         struct usb_device *usbdev;
1246         struct dlfb_data *dev;
1247         struct fb_info *info;
1248         int videomemorysize;
1249         int i;
1250         unsigned char *videomemory;
1251         int retval = -ENOMEM;
1252         struct fb_var_screeninfo *var;
1253         int registered = 0;
1254         u16 *pix_framebuffer;
1255
1256         /* usb initialization */
1257
1258         usbdev = interface_to_usbdev(interface);
1259
1260         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1261         if (dev == NULL) {
1262                 err("dlfb_usb_probe: failed alloc of dev struct\n");
1263                 goto error;
1264         }
1265
1266         /* we need to wait for both usb and fbdev to spin down on disconnect */
1267         kref_init(&dev->kref); /* matching kref_put in usb .disconnect fn */
1268         kref_get(&dev->kref); /* matching kref_put in .fb_destroy function*/
1269
1270         dev->udev = usbdev;
1271         dev->gdev = &usbdev->dev; /* our generic struct device * */
1272         usb_set_intfdata(interface, dev);
1273
1274         if (!dlfb_alloc_urb_list(dev, WRITES_IN_FLIGHT, MAX_TRANSFER)) {
1275                 retval = -ENOMEM;
1276                 dl_err("dlfb_alloc_urb_list failed\n");
1277                 goto error;
1278         }
1279
1280         mutex_init(&dev->fb_open_lock);
1281
1282         /* We don't register a new USB class. Our client interface is fbdev */
1283
1284         /* allocates framebuffer driver structure, not framebuffer memory */
1285         info = framebuffer_alloc(0, &usbdev->dev);
1286         if (!info) {
1287                 retval = -ENOMEM;
1288                 dl_err("framebuffer_alloc failed\n");
1289                 goto error;
1290         }
1291         dev->info = info;
1292         info->par = dev;
1293         info->pseudo_palette = dev->pseudo_palette;
1294         info->fbops = &dlfb_ops;
1295
1296         var = &info->var;
1297
1298         /* TODO set limit based on actual SKU detection */
1299         dev->sku_pixel_limit = 2048 * 1152;
1300
1301         INIT_LIST_HEAD(&info->modelist);
1302         dlfb_parse_edid(dev, var, info);
1303
1304         /*
1305          * ok, now that we've got the size info, we can alloc our framebuffer.
1306          */
1307         info->fix = dlfb_fix;
1308         info->fix.line_length = var->xres * (var->bits_per_pixel / 8);
1309         videomemorysize = info->fix.line_length * var->yres;
1310
1311         /*
1312          * The big chunk of system memory we use as a virtual framebuffer.
1313          * TODO: Handle fbcon cursor code calling blit in interrupt context
1314          */
1315         videomemory = vmalloc(videomemorysize);
1316         if (!videomemory) {
1317                 retval = -ENOMEM;
1318                 dl_err("Virtual framebuffer alloc failed\n");
1319                 goto error;
1320         }
1321
1322         info->screen_base = videomemory;
1323         info->fix.smem_len = PAGE_ALIGN(videomemorysize);
1324         info->fix.smem_start = (unsigned long) videomemory;
1325         info->flags = udlfb_info_flags;
1326
1327
1328         /*
1329          * Second framebuffer copy, mirroring the state of the framebuffer
1330          * on the physical USB device. We can function without this.
1331          * But with imperfect damage info we may end up sending pixels over USB
1332          * that were, in fact, unchanged -- wasting limited USB bandwidth
1333          */
1334         dev->backing_buffer = vmalloc(videomemorysize);
1335         if (!dev->backing_buffer)
1336                 dl_warn("No shadow/backing buffer allcoated\n");
1337         else
1338                 memset(dev->backing_buffer, 0, videomemorysize);
1339
1340         retval = fb_alloc_cmap(&info->cmap, 256, 0);
1341         if (retval < 0) {
1342                 dl_err("fb_alloc_cmap failed %x\n", retval);
1343                 goto error;
1344         }
1345
1346         /* ready to begin using device */
1347
1348 #ifdef CONFIG_FB_DEFERRED_IO
1349         atomic_set(&dev->use_defio, 1);
1350 #endif
1351         atomic_set(&dev->usb_active, 1);
1352         dlfb_select_std_channel(dev);
1353
1354         dlfb_ops_check_var(var, info);
1355         dlfb_ops_set_par(info);
1356
1357         /* paint greenscreen */
1358         pix_framebuffer = (u16 *) videomemory;
1359         for (i = 0; i < videomemorysize / 2; i++)
1360                 pix_framebuffer[i] = 0x37e6;
1361
1362         dlfb_handle_damage(dev, 0, 0, info->var.xres, info->var.yres,
1363                                 videomemory);
1364
1365         retval = register_framebuffer(info);
1366         if (retval < 0) {
1367                 dl_err("register_framebuffer failed %d\n", retval);
1368                 goto error;
1369         }
1370         registered = 1;
1371
1372         for (i = 0; i < ARRAY_SIZE(fb_device_attrs); i++)
1373                 device_create_file(info->dev, &fb_device_attrs[i]);
1374
1375         device_create_bin_file(info->dev, &edid_attr);
1376
1377         dl_err("DisplayLink USB device /dev/fb%d attached. %dx%d resolution."
1378                         " Using %dK framebuffer memory\n", info->node,
1379                         var->xres, var->yres,
1380                         ((dev->backing_buffer) ?
1381                         videomemorysize * 2 : videomemorysize) >> 10);
1382         return 0;
1383
1384 error:
1385         if (dev) {
1386                 if (registered) {
1387                         unregister_framebuffer(info);
1388                         dlfb_ops_destroy(info);
1389                 } else
1390                         kref_put(&dev->kref, dlfb_delete);
1391
1392                 if (dev->urbs.count > 0)
1393                         dlfb_free_urb_list(dev);
1394                 kref_put(&dev->kref, dlfb_delete); /* last ref from kref_init */
1395
1396                 /* dev has been deallocated. Do not dereference */
1397         }
1398
1399         return retval;
1400 }
1401
1402 static void dlfb_usb_disconnect(struct usb_interface *interface)
1403 {
1404         struct dlfb_data *dev;
1405         struct fb_info *info;
1406         int i;
1407
1408         dev = usb_get_intfdata(interface);
1409         info = dev->info;
1410
1411         /* when non-active we'll update virtual framebuffer, but no new urbs */
1412         atomic_set(&dev->usb_active, 0);
1413
1414         usb_set_intfdata(interface, NULL);
1415
1416         for (i = 0; i < ARRAY_SIZE(fb_device_attrs); i++)
1417                 device_remove_file(info->dev, &fb_device_attrs[i]);
1418
1419         device_remove_bin_file(info->dev, &edid_attr);
1420
1421         /* this function will wait for all in-flight urbs to complete */
1422         dlfb_free_urb_list(dev);
1423
1424         if (info) {
1425                 dl_notice("Detaching /dev/fb%d\n", info->node);
1426                 unregister_framebuffer(info);
1427                 dlfb_ops_destroy(info);
1428         }
1429
1430         /* release reference taken by kref_init in probe() */
1431         kref_put(&dev->kref, dlfb_delete);
1432
1433         /* consider dlfb_data freed */
1434
1435         return;
1436 }
1437
1438 static struct usb_driver dlfb_driver = {
1439         .name = "udlfb",
1440         .probe = dlfb_usb_probe,
1441         .disconnect = dlfb_usb_disconnect,
1442         .id_table = id_table,
1443 };
1444
1445 static int __init dlfb_module_init(void)
1446 {
1447         int res;
1448
1449         res = usb_register(&dlfb_driver);
1450         if (res)
1451                 err("usb_register failed. Error number %d", res);
1452
1453         printk(KERN_INFO "VMODES initialized\n");
1454
1455         return res;
1456 }
1457
1458 static void __exit dlfb_module_exit(void)
1459 {
1460         usb_deregister(&dlfb_driver);
1461 }
1462
1463 module_init(dlfb_module_init);
1464 module_exit(dlfb_module_exit);
1465
1466 static void dlfb_urb_completion(struct urb *urb)
1467 {
1468         struct urb_node *unode = urb->context;
1469         struct dlfb_data *dev = unode->dev;
1470         unsigned long flags;
1471
1472         /* sync/async unlink faults aren't errors */
1473         if (urb->status) {
1474                 if (!(urb->status == -ENOENT ||
1475                     urb->status == -ECONNRESET ||
1476                     urb->status == -ESHUTDOWN)) {
1477                         dl_err("%s - nonzero write bulk status received: %d\n",
1478                                 __func__, urb->status);
1479                         atomic_set(&dev->lost_pixels, 1);
1480                 }
1481         }
1482
1483         urb->transfer_buffer_length = dev->urbs.size; /* reset to actual */
1484
1485         spin_lock_irqsave(&dev->urbs.lock, flags);
1486         list_add_tail(&unode->entry, &dev->urbs.list);
1487         dev->urbs.available++;
1488         spin_unlock_irqrestore(&dev->urbs.lock, flags);
1489
1490         up(&dev->urbs.limit_sem);
1491 }
1492
1493 static void dlfb_free_urb_list(struct dlfb_data *dev)
1494 {
1495         int count = dev->urbs.count;
1496         struct list_head *node;
1497         struct urb_node *unode;
1498         struct urb *urb;
1499         int ret;
1500         unsigned long flags;
1501
1502         dl_notice("Waiting for completes and freeing all render urbs\n");
1503
1504         /* keep waiting and freeing, until we've got 'em all */
1505         while (count--) {
1506                 /* Timeout means a memory leak and/or fault */
1507                 ret = down_timeout(&dev->urbs.limit_sem, FREE_URB_TIMEOUT);
1508                 if (ret) {
1509                         BUG_ON(ret);
1510                         break;
1511                 }
1512                 spin_lock_irqsave(&dev->urbs.lock, flags);
1513
1514                 node = dev->urbs.list.next; /* have reserved one with sem */
1515                 list_del_init(node);
1516
1517                 spin_unlock_irqrestore(&dev->urbs.lock, flags);
1518
1519                 unode = list_entry(node, struct urb_node, entry);
1520                 urb = unode->urb;
1521
1522                 /* Free each separately allocated piece */
1523                 usb_free_coherent(urb->dev, dev->urbs.size,
1524                                   urb->transfer_buffer, urb->transfer_dma);
1525                 usb_free_urb(urb);
1526                 kfree(node);
1527         }
1528
1529         kref_put(&dev->kref, dlfb_delete);
1530
1531 }
1532
1533 static int dlfb_alloc_urb_list(struct dlfb_data *dev, int count, size_t size)
1534 {
1535         int i = 0;
1536         struct urb *urb;
1537         struct urb_node *unode;
1538         char *buf;
1539
1540         spin_lock_init(&dev->urbs.lock);
1541
1542         dev->urbs.size = size;
1543         INIT_LIST_HEAD(&dev->urbs.list);
1544
1545         while (i < count) {
1546                 unode = kzalloc(sizeof(struct urb_node), GFP_KERNEL);
1547                 if (!unode)
1548                         break;
1549                 unode->dev = dev;
1550
1551                 urb = usb_alloc_urb(0, GFP_KERNEL);
1552                 if (!urb) {
1553                         kfree(unode);
1554                         break;
1555                 }
1556                 unode->urb = urb;
1557
1558                 buf = usb_alloc_coherent(dev->udev, MAX_TRANSFER, GFP_KERNEL,
1559                                          &urb->transfer_dma);
1560                 if (!buf) {
1561                         kfree(unode);
1562                         usb_free_urb(urb);
1563                         break;
1564                 }
1565
1566                 /* urb->transfer_buffer_length set to actual before submit */
1567                 usb_fill_bulk_urb(urb, dev->udev, usb_sndbulkpipe(dev->udev, 1),
1568                         buf, size, dlfb_urb_completion, unode);
1569                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1570
1571                 list_add_tail(&unode->entry, &dev->urbs.list);
1572
1573                 i++;
1574         }
1575
1576         sema_init(&dev->urbs.limit_sem, i);
1577         dev->urbs.count = i;
1578         dev->urbs.available = i;
1579
1580         kref_get(&dev->kref); /* released in free_render_urbs() */
1581
1582         dl_notice("allocated %d %d byte urbs\n", i, (int) size);
1583
1584         return i;
1585 }
1586
1587 static struct urb *dlfb_get_urb(struct dlfb_data *dev)
1588 {
1589         int ret = 0;
1590         struct list_head *entry;
1591         struct urb_node *unode;
1592         struct urb *urb = NULL;
1593         unsigned long flags;
1594
1595         /* Wait for an in-flight buffer to complete and get re-queued */
1596         ret = down_timeout(&dev->urbs.limit_sem, GET_URB_TIMEOUT);
1597         if (ret) {
1598                 atomic_set(&dev->lost_pixels, 1);
1599                 dl_err("wait for urb interrupted: %x\n", ret);
1600                 goto error;
1601         }
1602
1603         spin_lock_irqsave(&dev->urbs.lock, flags);
1604
1605         BUG_ON(list_empty(&dev->urbs.list)); /* reserved one with limit_sem */
1606         entry = dev->urbs.list.next;
1607         list_del_init(entry);
1608         dev->urbs.available--;
1609
1610         spin_unlock_irqrestore(&dev->urbs.lock, flags);
1611
1612         unode = list_entry(entry, struct urb_node, entry);
1613         urb = unode->urb;
1614
1615 error:
1616         return urb;
1617 }
1618
1619 static int dlfb_submit_urb(struct dlfb_data *dev, struct urb *urb, size_t len)
1620 {
1621         int ret;
1622
1623         BUG_ON(len > dev->urbs.size);
1624
1625         urb->transfer_buffer_length = len; /* set to actual payload len */
1626         ret = usb_submit_urb(urb, GFP_KERNEL);
1627         if (ret) {
1628                 dlfb_urb_completion(urb); /* because no one else will */
1629                 atomic_set(&dev->lost_pixels, 1);
1630                 dl_err("usb_submit_urb error %x\n", ret);
1631         }
1632         return ret;
1633 }
1634
1635 MODULE_AUTHOR("Roberto De Ioris <roberto@unbit.it>, "
1636               "Jaya Kumar <jayakumar.lkml@gmail.com>, "
1637               "Bernie Thompson <bernie@plugable.com>");
1638 MODULE_DESCRIPTION("DisplayLink kernel framebuffer driver");
1639 MODULE_LICENSE("GPL");
1640