OSDN Git Service

udlfb: fix display corruption of the last line
[uclinux-h8/linux.git] / drivers / video / fbdev / 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 #include <linux/prefetch.h>
29 #include <linux/delay.h>
30 #include <asm/unaligned.h>
31 #include <video/udlfb.h>
32 #include "edid.h"
33
34 static const struct fb_fix_screeninfo dlfb_fix = {
35         .id =           "udlfb",
36         .type =         FB_TYPE_PACKED_PIXELS,
37         .visual =       FB_VISUAL_TRUECOLOR,
38         .xpanstep =     0,
39         .ypanstep =     0,
40         .ywrapstep =    0,
41         .accel =        FB_ACCEL_NONE,
42 };
43
44 static const u32 udlfb_info_flags = FBINFO_DEFAULT | FBINFO_READS_FAST |
45                 FBINFO_VIRTFB |
46                 FBINFO_HWACCEL_IMAGEBLIT | FBINFO_HWACCEL_FILLRECT |
47                 FBINFO_HWACCEL_COPYAREA | FBINFO_MISC_ALWAYS_SETPAR;
48
49 /*
50  * There are many DisplayLink-based graphics products, all with unique PIDs.
51  * So we match on DisplayLink's VID + Vendor-Defined Interface Class (0xff)
52  * We also require a match on SubClass (0x00) and Protocol (0x00),
53  * which is compatible with all known USB 2.0 era graphics chips and firmware,
54  * but allows DisplayLink to increment those for any future incompatible chips
55  */
56 static const struct usb_device_id id_table[] = {
57         {.idVendor = 0x17e9,
58          .bInterfaceClass = 0xff,
59          .bInterfaceSubClass = 0x00,
60          .bInterfaceProtocol = 0x00,
61          .match_flags = USB_DEVICE_ID_MATCH_VENDOR |
62                 USB_DEVICE_ID_MATCH_INT_CLASS |
63                 USB_DEVICE_ID_MATCH_INT_SUBCLASS |
64                 USB_DEVICE_ID_MATCH_INT_PROTOCOL,
65         },
66         {},
67 };
68 MODULE_DEVICE_TABLE(usb, id_table);
69
70 /* module options */
71 static bool console = 1; /* Allow fbcon to open framebuffer */
72 static bool fb_defio = 1;  /* Detect mmap writes using page faults */
73 static bool shadow = 1; /* Optionally disable shadow framebuffer */
74 static int pixel_limit; /* Optionally force a pixel resolution limit */
75
76 /* dlfb keeps a list of urbs for efficient bulk transfers */
77 static void dlfb_urb_completion(struct urb *urb);
78 static struct urb *dlfb_get_urb(struct dlfb_data *dlfb);
79 static int dlfb_submit_urb(struct dlfb_data *dlfb, struct urb * urb, size_t len);
80 static int dlfb_alloc_urb_list(struct dlfb_data *dlfb, int count, size_t size);
81 static void dlfb_free_urb_list(struct dlfb_data *dlfb);
82
83 /*
84  * All DisplayLink bulk operations start with 0xAF, followed by specific code
85  * All operations are written to buffers which then later get sent to device
86  */
87 static char *dlfb_set_register(char *buf, u8 reg, u8 val)
88 {
89         *buf++ = 0xAF;
90         *buf++ = 0x20;
91         *buf++ = reg;
92         *buf++ = val;
93         return buf;
94 }
95
96 static char *dlfb_vidreg_lock(char *buf)
97 {
98         return dlfb_set_register(buf, 0xFF, 0x00);
99 }
100
101 static char *dlfb_vidreg_unlock(char *buf)
102 {
103         return dlfb_set_register(buf, 0xFF, 0xFF);
104 }
105
106 /*
107  * Map FB_BLANK_* to DisplayLink register
108  * DLReg FB_BLANK_*
109  * ----- -----------------------------
110  *  0x00 FB_BLANK_UNBLANK (0)
111  *  0x01 FB_BLANK (1)
112  *  0x03 FB_BLANK_VSYNC_SUSPEND (2)
113  *  0x05 FB_BLANK_HSYNC_SUSPEND (3)
114  *  0x07 FB_BLANK_POWERDOWN (4) Note: requires modeset to come back
115  */
116 static char *dlfb_blanking(char *buf, int fb_blank)
117 {
118         u8 reg;
119
120         switch (fb_blank) {
121         case FB_BLANK_POWERDOWN:
122                 reg = 0x07;
123                 break;
124         case FB_BLANK_HSYNC_SUSPEND:
125                 reg = 0x05;
126                 break;
127         case FB_BLANK_VSYNC_SUSPEND:
128                 reg = 0x03;
129                 break;
130         case FB_BLANK_NORMAL:
131                 reg = 0x01;
132                 break;
133         default:
134                 reg = 0x00;
135         }
136
137         buf = dlfb_set_register(buf, 0x1F, reg);
138
139         return buf;
140 }
141
142 static char *dlfb_set_color_depth(char *buf, u8 selection)
143 {
144         return dlfb_set_register(buf, 0x00, selection);
145 }
146
147 static char *dlfb_set_base16bpp(char *wrptr, u32 base)
148 {
149         /* the base pointer is 16 bits wide, 0x20 is hi byte. */
150         wrptr = dlfb_set_register(wrptr, 0x20, base >> 16);
151         wrptr = dlfb_set_register(wrptr, 0x21, base >> 8);
152         return dlfb_set_register(wrptr, 0x22, base);
153 }
154
155 /*
156  * DisplayLink HW has separate 16bpp and 8bpp framebuffers.
157  * In 24bpp modes, the low 323 RGB bits go in the 8bpp framebuffer
158  */
159 static char *dlfb_set_base8bpp(char *wrptr, u32 base)
160 {
161         wrptr = dlfb_set_register(wrptr, 0x26, base >> 16);
162         wrptr = dlfb_set_register(wrptr, 0x27, base >> 8);
163         return dlfb_set_register(wrptr, 0x28, base);
164 }
165
166 static char *dlfb_set_register_16(char *wrptr, u8 reg, u16 value)
167 {
168         wrptr = dlfb_set_register(wrptr, reg, value >> 8);
169         return dlfb_set_register(wrptr, reg+1, value);
170 }
171
172 /*
173  * This is kind of weird because the controller takes some
174  * register values in a different byte order than other registers.
175  */
176 static char *dlfb_set_register_16be(char *wrptr, u8 reg, u16 value)
177 {
178         wrptr = dlfb_set_register(wrptr, reg, value);
179         return dlfb_set_register(wrptr, reg+1, value >> 8);
180 }
181
182 /*
183  * LFSR is linear feedback shift register. The reason we have this is
184  * because the display controller needs to minimize the clock depth of
185  * various counters used in the display path. So this code reverses the
186  * provided value into the lfsr16 value by counting backwards to get
187  * the value that needs to be set in the hardware comparator to get the
188  * same actual count. This makes sense once you read above a couple of
189  * times and think about it from a hardware perspective.
190  */
191 static u16 dlfb_lfsr16(u16 actual_count)
192 {
193         u32 lv = 0xFFFF; /* This is the lfsr value that the hw starts with */
194
195         while (actual_count--) {
196                 lv =     ((lv << 1) |
197                         (((lv >> 15) ^ (lv >> 4) ^ (lv >> 2) ^ (lv >> 1)) & 1))
198                         & 0xFFFF;
199         }
200
201         return (u16) lv;
202 }
203
204 /*
205  * This does LFSR conversion on the value that is to be written.
206  * See LFSR explanation above for more detail.
207  */
208 static char *dlfb_set_register_lfsr16(char *wrptr, u8 reg, u16 value)
209 {
210         return dlfb_set_register_16(wrptr, reg, dlfb_lfsr16(value));
211 }
212
213 /*
214  * This takes a standard fbdev screeninfo struct and all of its monitor mode
215  * details and converts them into the DisplayLink equivalent register commands.
216  */
217 static char *dlfb_set_vid_cmds(char *wrptr, struct fb_var_screeninfo *var)
218 {
219         u16 xds, yds;
220         u16 xde, yde;
221         u16 yec;
222
223         /* x display start */
224         xds = var->left_margin + var->hsync_len;
225         wrptr = dlfb_set_register_lfsr16(wrptr, 0x01, xds);
226         /* x display end */
227         xde = xds + var->xres;
228         wrptr = dlfb_set_register_lfsr16(wrptr, 0x03, xde);
229
230         /* y display start */
231         yds = var->upper_margin + var->vsync_len;
232         wrptr = dlfb_set_register_lfsr16(wrptr, 0x05, yds);
233         /* y display end */
234         yde = yds + var->yres;
235         wrptr = dlfb_set_register_lfsr16(wrptr, 0x07, yde);
236
237         /* x end count is active + blanking - 1 */
238         wrptr = dlfb_set_register_lfsr16(wrptr, 0x09,
239                         xde + var->right_margin - 1);
240
241         /* libdlo hardcodes hsync start to 1 */
242         wrptr = dlfb_set_register_lfsr16(wrptr, 0x0B, 1);
243
244         /* hsync end is width of sync pulse + 1 */
245         wrptr = dlfb_set_register_lfsr16(wrptr, 0x0D, var->hsync_len + 1);
246
247         /* hpixels is active pixels */
248         wrptr = dlfb_set_register_16(wrptr, 0x0F, var->xres);
249
250         /* yendcount is vertical active + vertical blanking */
251         yec = var->yres + var->upper_margin + var->lower_margin +
252                         var->vsync_len;
253         wrptr = dlfb_set_register_lfsr16(wrptr, 0x11, yec);
254
255         /* libdlo hardcodes vsync start to 0 */
256         wrptr = dlfb_set_register_lfsr16(wrptr, 0x13, 0);
257
258         /* vsync end is width of vsync pulse */
259         wrptr = dlfb_set_register_lfsr16(wrptr, 0x15, var->vsync_len);
260
261         /* vpixels is active pixels */
262         wrptr = dlfb_set_register_16(wrptr, 0x17, var->yres);
263
264         /* convert picoseconds to 5kHz multiple for pclk5k = x * 1E12/5k */
265         wrptr = dlfb_set_register_16be(wrptr, 0x1B,
266                         200*1000*1000/var->pixclock);
267
268         return wrptr;
269 }
270
271 /*
272  * This takes a standard fbdev screeninfo struct that was fetched or prepared
273  * and then generates the appropriate command sequence that then drives the
274  * display controller.
275  */
276 static int dlfb_set_video_mode(struct dlfb_data *dlfb,
277                                 struct fb_var_screeninfo *var)
278 {
279         char *buf;
280         char *wrptr;
281         int retval;
282         int writesize;
283         struct urb *urb;
284
285         if (!atomic_read(&dlfb->usb_active))
286                 return -EPERM;
287
288         urb = dlfb_get_urb(dlfb);
289         if (!urb)
290                 return -ENOMEM;
291
292         buf = (char *) urb->transfer_buffer;
293
294         /*
295         * This first section has to do with setting the base address on the
296         * controller * associated with the display. There are 2 base
297         * pointers, currently, we only * use the 16 bpp segment.
298         */
299         wrptr = dlfb_vidreg_lock(buf);
300         wrptr = dlfb_set_color_depth(wrptr, 0x00);
301         /* set base for 16bpp segment to 0 */
302         wrptr = dlfb_set_base16bpp(wrptr, 0);
303         /* set base for 8bpp segment to end of fb */
304         wrptr = dlfb_set_base8bpp(wrptr, dlfb->info->fix.smem_len);
305
306         wrptr = dlfb_set_vid_cmds(wrptr, var);
307         wrptr = dlfb_blanking(wrptr, FB_BLANK_UNBLANK);
308         wrptr = dlfb_vidreg_unlock(wrptr);
309
310         writesize = wrptr - buf;
311
312         retval = dlfb_submit_urb(dlfb, urb, writesize);
313
314         dlfb->blank_mode = FB_BLANK_UNBLANK;
315
316         return retval;
317 }
318
319 static int dlfb_ops_mmap(struct fb_info *info, struct vm_area_struct *vma)
320 {
321         unsigned long start = vma->vm_start;
322         unsigned long size = vma->vm_end - vma->vm_start;
323         unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
324         unsigned long page, pos;
325
326         if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))
327                 return -EINVAL;
328         if (size > info->fix.smem_len)
329                 return -EINVAL;
330         if (offset > info->fix.smem_len - size)
331                 return -EINVAL;
332
333         pos = (unsigned long)info->fix.smem_start + offset;
334
335         dev_dbg(info->dev, "mmap() framebuffer addr:%lu size:%lu\n",
336                 pos, size);
337
338         while (size > 0) {
339                 page = vmalloc_to_pfn((void *)pos);
340                 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
341                         return -EAGAIN;
342
343                 start += PAGE_SIZE;
344                 pos += PAGE_SIZE;
345                 if (size > PAGE_SIZE)
346                         size -= PAGE_SIZE;
347                 else
348                         size = 0;
349         }
350
351         return 0;
352 }
353
354 /*
355  * Trims identical data from front and back of line
356  * Sets new front buffer address and width
357  * And returns byte count of identical pixels
358  * Assumes CPU natural alignment (unsigned long)
359  * for back and front buffer ptrs and width
360  */
361 static int dlfb_trim_hline(const u8 *bback, const u8 **bfront, int *width_bytes)
362 {
363         int j, k;
364         const unsigned long *back = (const unsigned long *) bback;
365         const unsigned long *front = (const unsigned long *) *bfront;
366         const int width = *width_bytes / sizeof(unsigned long);
367         int identical = width;
368         int start = width;
369         int end = width;
370
371         prefetch((void *) front);
372         prefetch((void *) back);
373
374         for (j = 0; j < width; j++) {
375                 if (back[j] != front[j]) {
376                         start = j;
377                         break;
378                 }
379         }
380
381         for (k = width - 1; k > j; k--) {
382                 if (back[k] != front[k]) {
383                         end = k+1;
384                         break;
385                 }
386         }
387
388         identical = start + (width - end);
389         *bfront = (u8 *) &front[start];
390         *width_bytes = (end - start) * sizeof(unsigned long);
391
392         return identical * sizeof(unsigned long);
393 }
394
395 /*
396  * Render a command stream for an encoded horizontal line segment of pixels.
397  *
398  * A command buffer holds several commands.
399  * It always begins with a fresh command header
400  * (the protocol doesn't require this, but we enforce it to allow
401  * multiple buffers to be potentially encoded and sent in parallel).
402  * A single command encodes one contiguous horizontal line of pixels
403  *
404  * The function relies on the client to do all allocation, so that
405  * rendering can be done directly to output buffers (e.g. USB URBs).
406  * The function fills the supplied command buffer, providing information
407  * on where it left off, so the client may call in again with additional
408  * buffers if the line will take several buffers to complete.
409  *
410  * A single command can transmit a maximum of 256 pixels,
411  * regardless of the compression ratio (protocol design limit).
412  * To the hardware, 0 for a size byte means 256
413  *
414  * Rather than 256 pixel commands which are either rl or raw encoded,
415  * the rlx command simply assumes alternating raw and rl spans within one cmd.
416  * This has a slightly larger header overhead, but produces more even results.
417  * It also processes all data (read and write) in a single pass.
418  * Performance benchmarks of common cases show it having just slightly better
419  * compression than 256 pixel raw or rle commands, with similar CPU consumpion.
420  * But for very rl friendly data, will compress not quite as well.
421  */
422 static void dlfb_compress_hline(
423         const uint16_t **pixel_start_ptr,
424         const uint16_t *const pixel_end,
425         uint32_t *device_address_ptr,
426         uint8_t **command_buffer_ptr,
427         const uint8_t *const cmd_buffer_end)
428 {
429         const uint16_t *pixel = *pixel_start_ptr;
430         uint32_t dev_addr  = *device_address_ptr;
431         uint8_t *cmd = *command_buffer_ptr;
432
433         while ((pixel_end > pixel) &&
434                (cmd_buffer_end - MIN_RLX_CMD_BYTES > cmd)) {
435                 uint8_t *raw_pixels_count_byte = NULL;
436                 uint8_t *cmd_pixels_count_byte = NULL;
437                 const uint16_t *raw_pixel_start = NULL;
438                 const uint16_t *cmd_pixel_start, *cmd_pixel_end = NULL;
439
440                 prefetchw((void *) cmd); /* pull in one cache line at least */
441
442                 *cmd++ = 0xAF;
443                 *cmd++ = 0x6B;
444                 *cmd++ = dev_addr >> 16;
445                 *cmd++ = dev_addr >> 8;
446                 *cmd++ = dev_addr;
447
448                 cmd_pixels_count_byte = cmd++; /*  we'll know this later */
449                 cmd_pixel_start = pixel;
450
451                 raw_pixels_count_byte = cmd++; /*  we'll know this later */
452                 raw_pixel_start = pixel;
453
454                 cmd_pixel_end = pixel + min3(MAX_CMD_PIXELS + 1UL,
455                                         (unsigned long)(pixel_end - pixel),
456                                         (unsigned long)(cmd_buffer_end - 1 - cmd) / BPP);
457
458                 prefetch_range((void *) pixel, (u8 *)cmd_pixel_end - (u8 *)pixel);
459
460                 while (pixel < cmd_pixel_end) {
461                         const uint16_t * const repeating_pixel = pixel;
462
463                         put_unaligned_be16(*pixel, cmd);
464                         cmd += 2;
465                         pixel++;
466
467                         if (unlikely((pixel < cmd_pixel_end) &&
468                                      (*pixel == *repeating_pixel))) {
469                                 /* go back and fill in raw pixel count */
470                                 *raw_pixels_count_byte = ((repeating_pixel -
471                                                 raw_pixel_start) + 1) & 0xFF;
472
473                                 while ((pixel < cmd_pixel_end)
474                                        && (*pixel == *repeating_pixel)) {
475                                         pixel++;
476                                 }
477
478                                 /* immediately after raw data is repeat byte */
479                                 *cmd++ = ((pixel - repeating_pixel) - 1) & 0xFF;
480
481                                 /* Then start another raw pixel span */
482                                 raw_pixel_start = pixel;
483                                 raw_pixels_count_byte = cmd++;
484                         }
485                 }
486
487                 if (pixel > raw_pixel_start) {
488                         /* finalize last RAW span */
489                         *raw_pixels_count_byte = (pixel-raw_pixel_start) & 0xFF;
490                 } else {
491                         /* undo unused byte */
492                         cmd--;
493                 }
494
495                 *cmd_pixels_count_byte = (pixel - cmd_pixel_start) & 0xFF;
496                 dev_addr += (u8 *)pixel - (u8 *)cmd_pixel_start;
497         }
498
499         if (cmd_buffer_end - MIN_RLX_CMD_BYTES <= cmd) {
500                 /* Fill leftover bytes with no-ops */
501                 if (cmd_buffer_end > cmd)
502                         memset(cmd, 0xAF, cmd_buffer_end - cmd);
503                 cmd = (uint8_t *) cmd_buffer_end;
504         }
505
506         *command_buffer_ptr = cmd;
507         *pixel_start_ptr = pixel;
508         *device_address_ptr = dev_addr;
509 }
510
511 /*
512  * There are 3 copies of every pixel: The front buffer that the fbdev
513  * client renders to, the actual framebuffer across the USB bus in hardware
514  * (that we can only write to, slowly, and can never read), and (optionally)
515  * our shadow copy that tracks what's been sent to that hardware buffer.
516  */
517 static int dlfb_render_hline(struct dlfb_data *dlfb, struct urb **urb_ptr,
518                               const char *front, char **urb_buf_ptr,
519                               u32 byte_offset, u32 byte_width,
520                               int *ident_ptr, int *sent_ptr)
521 {
522         const u8 *line_start, *line_end, *next_pixel;
523         u32 dev_addr = dlfb->base16 + byte_offset;
524         struct urb *urb = *urb_ptr;
525         u8 *cmd = *urb_buf_ptr;
526         u8 *cmd_end = (u8 *) urb->transfer_buffer + urb->transfer_buffer_length;
527
528         line_start = (u8 *) (front + byte_offset);
529         next_pixel = line_start;
530         line_end = next_pixel + byte_width;
531
532         if (dlfb->backing_buffer) {
533                 int offset;
534                 const u8 *back_start = (u8 *) (dlfb->backing_buffer
535                                                 + byte_offset);
536
537                 *ident_ptr += dlfb_trim_hline(back_start, &next_pixel,
538                         &byte_width);
539
540                 offset = next_pixel - line_start;
541                 line_end = next_pixel + byte_width;
542                 dev_addr += offset;
543                 back_start += offset;
544                 line_start += offset;
545
546                 memcpy((char *)back_start, (char *) line_start,
547                        byte_width);
548         }
549
550         while (next_pixel < line_end) {
551
552                 dlfb_compress_hline((const uint16_t **) &next_pixel,
553                              (const uint16_t *) line_end, &dev_addr,
554                         (u8 **) &cmd, (u8 *) cmd_end);
555
556                 if (cmd >= cmd_end) {
557                         int len = cmd - (u8 *) urb->transfer_buffer;
558                         if (dlfb_submit_urb(dlfb, urb, len))
559                                 return 1; /* lost pixels is set */
560                         *sent_ptr += len;
561                         urb = dlfb_get_urb(dlfb);
562                         if (!urb)
563                                 return 1; /* lost_pixels is set */
564                         *urb_ptr = urb;
565                         cmd = urb->transfer_buffer;
566                         cmd_end = &cmd[urb->transfer_buffer_length];
567                 }
568         }
569
570         *urb_buf_ptr = cmd;
571
572         return 0;
573 }
574
575 static int dlfb_handle_damage(struct dlfb_data *dlfb, int x, int y,
576                int width, int height, char *data)
577 {
578         int i, ret;
579         char *cmd;
580         cycles_t start_cycles, end_cycles;
581         int bytes_sent = 0;
582         int bytes_identical = 0;
583         struct urb *urb;
584         int aligned_x;
585
586         start_cycles = get_cycles();
587
588         aligned_x = DL_ALIGN_DOWN(x, sizeof(unsigned long));
589         width = DL_ALIGN_UP(width + (x-aligned_x), sizeof(unsigned long));
590         x = aligned_x;
591
592         if ((width <= 0) ||
593             (x + width > dlfb->info->var.xres) ||
594             (y + height > dlfb->info->var.yres))
595                 return -EINVAL;
596
597         if (!atomic_read(&dlfb->usb_active))
598                 return 0;
599
600         urb = dlfb_get_urb(dlfb);
601         if (!urb)
602                 return 0;
603         cmd = urb->transfer_buffer;
604
605         for (i = y; i < y + height ; i++) {
606                 const int line_offset = dlfb->info->fix.line_length * i;
607                 const int byte_offset = line_offset + (x * BPP);
608
609                 if (dlfb_render_hline(dlfb, &urb,
610                                       (char *) dlfb->info->fix.smem_start,
611                                       &cmd, byte_offset, width * BPP,
612                                       &bytes_identical, &bytes_sent))
613                         goto error;
614         }
615
616         if (cmd > (char *) urb->transfer_buffer) {
617                 int len;
618                 if (cmd < (char *) urb->transfer_buffer + urb->transfer_buffer_length)
619                         *cmd++ = 0xAF;
620                 /* Send partial buffer remaining before exiting */
621                 len = cmd - (char *) urb->transfer_buffer;
622                 ret = dlfb_submit_urb(dlfb, urb, len);
623                 bytes_sent += len;
624         } else
625                 dlfb_urb_completion(urb);
626
627 error:
628         atomic_add(bytes_sent, &dlfb->bytes_sent);
629         atomic_add(bytes_identical, &dlfb->bytes_identical);
630         atomic_add(width*height*2, &dlfb->bytes_rendered);
631         end_cycles = get_cycles();
632         atomic_add(((unsigned int) ((end_cycles - start_cycles)
633                     >> 10)), /* Kcycles */
634                    &dlfb->cpu_kcycles_used);
635
636         return 0;
637 }
638
639 /*
640  * Path triggered by usermode clients who write to filesystem
641  * e.g. cat filename > /dev/fb1
642  * Not used by X Windows or text-mode console. But useful for testing.
643  * Slow because of extra copy and we must assume all pixels dirty.
644  */
645 static ssize_t dlfb_ops_write(struct fb_info *info, const char __user *buf,
646                           size_t count, loff_t *ppos)
647 {
648         ssize_t result;
649         struct dlfb_data *dlfb = info->par;
650         u32 offset = (u32) *ppos;
651
652         result = fb_sys_write(info, buf, count, ppos);
653
654         if (result > 0) {
655                 int start = max((int)(offset / info->fix.line_length), 0);
656                 int lines = min((u32)((result / info->fix.line_length) + 1),
657                                 (u32)info->var.yres);
658
659                 dlfb_handle_damage(dlfb, 0, start, info->var.xres,
660                         lines, info->screen_base);
661         }
662
663         return result;
664 }
665
666 /* hardware has native COPY command (see libdlo), but not worth it for fbcon */
667 static void dlfb_ops_copyarea(struct fb_info *info,
668                                 const struct fb_copyarea *area)
669 {
670
671         struct dlfb_data *dlfb = info->par;
672
673         sys_copyarea(info, area);
674
675         dlfb_handle_damage(dlfb, area->dx, area->dy,
676                         area->width, area->height, info->screen_base);
677 }
678
679 static void dlfb_ops_imageblit(struct fb_info *info,
680                                 const struct fb_image *image)
681 {
682         struct dlfb_data *dlfb = info->par;
683
684         sys_imageblit(info, image);
685
686         dlfb_handle_damage(dlfb, image->dx, image->dy,
687                         image->width, image->height, info->screen_base);
688 }
689
690 static void dlfb_ops_fillrect(struct fb_info *info,
691                           const struct fb_fillrect *rect)
692 {
693         struct dlfb_data *dlfb = info->par;
694
695         sys_fillrect(info, rect);
696
697         dlfb_handle_damage(dlfb, rect->dx, rect->dy, rect->width,
698                               rect->height, info->screen_base);
699 }
700
701 /*
702  * NOTE: fb_defio.c is holding info->fbdefio.mutex
703  *   Touching ANY framebuffer memory that triggers a page fault
704  *   in fb_defio will cause a deadlock, when it also tries to
705  *   grab the same mutex.
706  */
707 static void dlfb_dpy_deferred_io(struct fb_info *info,
708                                 struct list_head *pagelist)
709 {
710         struct page *cur;
711         struct fb_deferred_io *fbdefio = info->fbdefio;
712         struct dlfb_data *dlfb = info->par;
713         struct urb *urb;
714         char *cmd;
715         cycles_t start_cycles, end_cycles;
716         int bytes_sent = 0;
717         int bytes_identical = 0;
718         int bytes_rendered = 0;
719
720         if (!fb_defio)
721                 return;
722
723         if (!atomic_read(&dlfb->usb_active))
724                 return;
725
726         start_cycles = get_cycles();
727
728         urb = dlfb_get_urb(dlfb);
729         if (!urb)
730                 return;
731
732         cmd = urb->transfer_buffer;
733
734         /* walk the written page list and render each to device */
735         list_for_each_entry(cur, &fbdefio->pagelist, lru) {
736
737                 if (dlfb_render_hline(dlfb, &urb, (char *) info->fix.smem_start,
738                                   &cmd, cur->index << PAGE_SHIFT,
739                                   PAGE_SIZE, &bytes_identical, &bytes_sent))
740                         goto error;
741                 bytes_rendered += PAGE_SIZE;
742         }
743
744         if (cmd > (char *) urb->transfer_buffer) {
745                 int len;
746                 if (cmd < (char *) urb->transfer_buffer + urb->transfer_buffer_length)
747                         *cmd++ = 0xAF;
748                 /* Send partial buffer remaining before exiting */
749                 len = cmd - (char *) urb->transfer_buffer;
750                 dlfb_submit_urb(dlfb, urb, len);
751                 bytes_sent += len;
752         } else
753                 dlfb_urb_completion(urb);
754
755 error:
756         atomic_add(bytes_sent, &dlfb->bytes_sent);
757         atomic_add(bytes_identical, &dlfb->bytes_identical);
758         atomic_add(bytes_rendered, &dlfb->bytes_rendered);
759         end_cycles = get_cycles();
760         atomic_add(((unsigned int) ((end_cycles - start_cycles)
761                     >> 10)), /* Kcycles */
762                    &dlfb->cpu_kcycles_used);
763 }
764
765 static int dlfb_get_edid(struct dlfb_data *dlfb, char *edid, int len)
766 {
767         int i, ret;
768         char *rbuf;
769
770         rbuf = kmalloc(2, GFP_KERNEL);
771         if (!rbuf)
772                 return 0;
773
774         for (i = 0; i < len; i++) {
775                 ret = usb_control_msg(dlfb->udev,
776                                       usb_rcvctrlpipe(dlfb->udev, 0), 0x02,
777                                       (0x80 | (0x02 << 5)), i << 8, 0xA1,
778                                       rbuf, 2, USB_CTRL_GET_TIMEOUT);
779                 if (ret < 2) {
780                         dev_err(&dlfb->udev->dev,
781                                 "Read EDID byte %d failed: %d\n", i, ret);
782                         i--;
783                         break;
784                 }
785                 edid[i] = rbuf[1];
786         }
787
788         kfree(rbuf);
789
790         return i;
791 }
792
793 static int dlfb_ops_ioctl(struct fb_info *info, unsigned int cmd,
794                                 unsigned long arg)
795 {
796
797         struct dlfb_data *dlfb = info->par;
798
799         if (!atomic_read(&dlfb->usb_active))
800                 return 0;
801
802         /* TODO: Update X server to get this from sysfs instead */
803         if (cmd == DLFB_IOCTL_RETURN_EDID) {
804                 void __user *edid = (void __user *)arg;
805                 if (copy_to_user(edid, dlfb->edid, dlfb->edid_size))
806                         return -EFAULT;
807                 return 0;
808         }
809
810         /* TODO: Help propose a standard fb.h ioctl to report mmap damage */
811         if (cmd == DLFB_IOCTL_REPORT_DAMAGE) {
812                 struct dloarea area;
813
814                 if (copy_from_user(&area, (void __user *)arg,
815                                   sizeof(struct dloarea)))
816                         return -EFAULT;
817
818                 /*
819                  * If we have a damage-aware client, turn fb_defio "off"
820                  * To avoid perf imact of unnecessary page fault handling.
821                  * Done by resetting the delay for this fb_info to a very
822                  * long period. Pages will become writable and stay that way.
823                  * Reset to normal value when all clients have closed this fb.
824                  */
825                 if (info->fbdefio)
826                         info->fbdefio->delay = DL_DEFIO_WRITE_DISABLE;
827
828                 if (area.x < 0)
829                         area.x = 0;
830
831                 if (area.x > info->var.xres)
832                         area.x = info->var.xres;
833
834                 if (area.y < 0)
835                         area.y = 0;
836
837                 if (area.y > info->var.yres)
838                         area.y = info->var.yres;
839
840                 dlfb_handle_damage(dlfb, area.x, area.y, area.w, area.h,
841                            info->screen_base);
842         }
843
844         return 0;
845 }
846
847 /* taken from vesafb */
848 static int
849 dlfb_ops_setcolreg(unsigned regno, unsigned red, unsigned green,
850                unsigned blue, unsigned transp, struct fb_info *info)
851 {
852         int err = 0;
853
854         if (regno >= info->cmap.len)
855                 return 1;
856
857         if (regno < 16) {
858                 if (info->var.red.offset == 10) {
859                         /* 1:5:5:5 */
860                         ((u32 *) (info->pseudo_palette))[regno] =
861                             ((red & 0xf800) >> 1) |
862                             ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11);
863                 } else {
864                         /* 0:5:6:5 */
865                         ((u32 *) (info->pseudo_palette))[regno] =
866                             ((red & 0xf800)) |
867                             ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11);
868                 }
869         }
870
871         return err;
872 }
873
874 /*
875  * It's common for several clients to have framebuffer open simultaneously.
876  * e.g. both fbcon and X. Makes things interesting.
877  * Assumes caller is holding info->lock (for open and release at least)
878  */
879 static int dlfb_ops_open(struct fb_info *info, int user)
880 {
881         struct dlfb_data *dlfb = info->par;
882
883         /*
884          * fbcon aggressively connects to first framebuffer it finds,
885          * preventing other clients (X) from working properly. Usually
886          * not what the user wants. Fail by default with option to enable.
887          */
888         if ((user == 0) && (!console))
889                 return -EBUSY;
890
891         /* If the USB device is gone, we don't accept new opens */
892         if (dlfb->virtualized)
893                 return -ENODEV;
894
895         dlfb->fb_count++;
896
897         kref_get(&dlfb->kref);
898
899         if (fb_defio && (info->fbdefio == NULL)) {
900                 /* enable defio at last moment if not disabled by client */
901
902                 struct fb_deferred_io *fbdefio;
903
904                 fbdefio = kzalloc(sizeof(struct fb_deferred_io), GFP_KERNEL);
905
906                 if (fbdefio) {
907                         fbdefio->delay = DL_DEFIO_WRITE_DELAY;
908                         fbdefio->deferred_io = dlfb_dpy_deferred_io;
909                 }
910
911                 info->fbdefio = fbdefio;
912                 fb_deferred_io_init(info);
913         }
914
915         dev_dbg(info->dev, "open, user=%d fb_info=%p count=%d\n",
916                 user, info, dlfb->fb_count);
917
918         return 0;
919 }
920
921 /*
922  * Called when all client interfaces to start transactions have been disabled,
923  * and all references to our device instance (dlfb_data) are released.
924  * Every transaction must have a reference, so we know are fully spun down
925  */
926 static void dlfb_free(struct kref *kref)
927 {
928         struct dlfb_data *dlfb = container_of(kref, struct dlfb_data, kref);
929
930         vfree(dlfb->backing_buffer);
931         kfree(dlfb->edid);
932         kfree(dlfb);
933 }
934
935 static void dlfb_free_framebuffer(struct dlfb_data *dlfb)
936 {
937         struct fb_info *info = dlfb->info;
938
939         if (info) {
940                 unregister_framebuffer(info);
941
942                 if (info->cmap.len != 0)
943                         fb_dealloc_cmap(&info->cmap);
944                 if (info->monspecs.modedb)
945                         fb_destroy_modedb(info->monspecs.modedb);
946                 vfree(info->screen_base);
947
948                 fb_destroy_modelist(&info->modelist);
949
950                 dlfb->info = NULL;
951
952                 /* Assume info structure is freed after this point */
953                 framebuffer_release(info);
954         }
955
956         /* ref taken in probe() as part of registering framebfufer */
957         kref_put(&dlfb->kref, dlfb_free);
958 }
959
960 static void dlfb_free_framebuffer_work(struct work_struct *work)
961 {
962         struct dlfb_data *dlfb = container_of(work, struct dlfb_data,
963                                              free_framebuffer_work.work);
964         dlfb_free_framebuffer(dlfb);
965 }
966 /*
967  * Assumes caller is holding info->lock mutex (for open and release at least)
968  */
969 static int dlfb_ops_release(struct fb_info *info, int user)
970 {
971         struct dlfb_data *dlfb = info->par;
972
973         dlfb->fb_count--;
974
975         /* We can't free fb_info here - fbmem will touch it when we return */
976         if (dlfb->virtualized && (dlfb->fb_count == 0))
977                 schedule_delayed_work(&dlfb->free_framebuffer_work, HZ);
978
979         if ((dlfb->fb_count == 0) && (info->fbdefio)) {
980                 fb_deferred_io_cleanup(info);
981                 kfree(info->fbdefio);
982                 info->fbdefio = NULL;
983                 info->fbops->fb_mmap = dlfb_ops_mmap;
984         }
985
986         dev_dbg(info->dev, "release, user=%d count=%d\n", user, dlfb->fb_count);
987
988         kref_put(&dlfb->kref, dlfb_free);
989
990         return 0;
991 }
992
993 /*
994  * Check whether a video mode is supported by the DisplayLink chip
995  * We start from monitor's modes, so don't need to filter that here
996  */
997 static int dlfb_is_valid_mode(struct fb_videomode *mode, struct dlfb_data *dlfb)
998 {
999         if (mode->xres * mode->yres > dlfb->sku_pixel_limit)
1000                 return 0;
1001
1002         return 1;
1003 }
1004
1005 static void dlfb_var_color_format(struct fb_var_screeninfo *var)
1006 {
1007         const struct fb_bitfield red = { 11, 5, 0 };
1008         const struct fb_bitfield green = { 5, 6, 0 };
1009         const struct fb_bitfield blue = { 0, 5, 0 };
1010
1011         var->bits_per_pixel = 16;
1012         var->red = red;
1013         var->green = green;
1014         var->blue = blue;
1015 }
1016
1017 static int dlfb_ops_check_var(struct fb_var_screeninfo *var,
1018                                 struct fb_info *info)
1019 {
1020         struct fb_videomode mode;
1021         struct dlfb_data *dlfb = info->par;
1022
1023         /* TODO: support dynamically changing framebuffer size */
1024         if ((var->xres * var->yres * 2) > info->fix.smem_len)
1025                 return -EINVAL;
1026
1027         /* set device-specific elements of var unrelated to mode */
1028         dlfb_var_color_format(var);
1029
1030         fb_var_to_videomode(&mode, var);
1031
1032         if (!dlfb_is_valid_mode(&mode, dlfb))
1033                 return -EINVAL;
1034
1035         return 0;
1036 }
1037
1038 static int dlfb_ops_set_par(struct fb_info *info)
1039 {
1040         struct dlfb_data *dlfb = info->par;
1041         int result;
1042         u16 *pix_framebuffer;
1043         int i;
1044
1045         result = dlfb_set_video_mode(dlfb, &info->var);
1046
1047         if ((result == 0) && (dlfb->fb_count == 0)) {
1048
1049                 /* paint greenscreen */
1050
1051                 pix_framebuffer = (u16 *) info->screen_base;
1052                 for (i = 0; i < info->fix.smem_len / 2; i++)
1053                         pix_framebuffer[i] = 0x37e6;
1054
1055                 dlfb_handle_damage(dlfb, 0, 0, info->var.xres, info->var.yres,
1056                                    info->screen_base);
1057         }
1058
1059         return result;
1060 }
1061
1062 /* To fonzi the jukebox (e.g. make blanking changes take effect) */
1063 static char *dlfb_dummy_render(char *buf)
1064 {
1065         *buf++ = 0xAF;
1066         *buf++ = 0x6A; /* copy */
1067         *buf++ = 0x00; /* from address*/
1068         *buf++ = 0x00;
1069         *buf++ = 0x00;
1070         *buf++ = 0x01; /* one pixel */
1071         *buf++ = 0x00; /* to address */
1072         *buf++ = 0x00;
1073         *buf++ = 0x00;
1074         return buf;
1075 }
1076
1077 /*
1078  * In order to come back from full DPMS off, we need to set the mode again
1079  */
1080 static int dlfb_ops_blank(int blank_mode, struct fb_info *info)
1081 {
1082         struct dlfb_data *dlfb = info->par;
1083         char *bufptr;
1084         struct urb *urb;
1085
1086         dev_dbg(info->dev, "blank, mode %d --> %d\n",
1087                 dlfb->blank_mode, blank_mode);
1088
1089         if ((dlfb->blank_mode == FB_BLANK_POWERDOWN) &&
1090             (blank_mode != FB_BLANK_POWERDOWN)) {
1091
1092                 /* returning from powerdown requires a fresh modeset */
1093                 dlfb_set_video_mode(dlfb, &info->var);
1094         }
1095
1096         urb = dlfb_get_urb(dlfb);
1097         if (!urb)
1098                 return 0;
1099
1100         bufptr = (char *) urb->transfer_buffer;
1101         bufptr = dlfb_vidreg_lock(bufptr);
1102         bufptr = dlfb_blanking(bufptr, blank_mode);
1103         bufptr = dlfb_vidreg_unlock(bufptr);
1104
1105         /* seems like a render op is needed to have blank change take effect */
1106         bufptr = dlfb_dummy_render(bufptr);
1107
1108         dlfb_submit_urb(dlfb, urb, bufptr -
1109                         (char *) urb->transfer_buffer);
1110
1111         dlfb->blank_mode = blank_mode;
1112
1113         return 0;
1114 }
1115
1116 static struct fb_ops dlfb_ops = {
1117         .owner = THIS_MODULE,
1118         .fb_read = fb_sys_read,
1119         .fb_write = dlfb_ops_write,
1120         .fb_setcolreg = dlfb_ops_setcolreg,
1121         .fb_fillrect = dlfb_ops_fillrect,
1122         .fb_copyarea = dlfb_ops_copyarea,
1123         .fb_imageblit = dlfb_ops_imageblit,
1124         .fb_mmap = dlfb_ops_mmap,
1125         .fb_ioctl = dlfb_ops_ioctl,
1126         .fb_open = dlfb_ops_open,
1127         .fb_release = dlfb_ops_release,
1128         .fb_blank = dlfb_ops_blank,
1129         .fb_check_var = dlfb_ops_check_var,
1130         .fb_set_par = dlfb_ops_set_par,
1131 };
1132
1133
1134 /*
1135  * Assumes &info->lock held by caller
1136  * Assumes no active clients have framebuffer open
1137  */
1138 static int dlfb_realloc_framebuffer(struct dlfb_data *dlfb, struct fb_info *info)
1139 {
1140         int old_len = info->fix.smem_len;
1141         int new_len;
1142         unsigned char *old_fb = info->screen_base;
1143         unsigned char *new_fb;
1144         unsigned char *new_back = NULL;
1145
1146         new_len = info->fix.line_length * info->var.yres;
1147
1148         if (PAGE_ALIGN(new_len) > old_len) {
1149                 /*
1150                  * Alloc system memory for virtual framebuffer
1151                  */
1152                 new_fb = vmalloc(new_len);
1153                 if (!new_fb) {
1154                         dev_err(info->dev, "Virtual framebuffer alloc failed\n");
1155                         return -ENOMEM;
1156                 }
1157
1158                 if (info->screen_base) {
1159                         memcpy(new_fb, old_fb, old_len);
1160                         vfree(info->screen_base);
1161                 }
1162
1163                 info->screen_base = new_fb;
1164                 info->fix.smem_len = PAGE_ALIGN(new_len);
1165                 info->fix.smem_start = (unsigned long) new_fb;
1166                 info->flags = udlfb_info_flags;
1167
1168                 /*
1169                  * Second framebuffer copy to mirror the framebuffer state
1170                  * on the physical USB device. We can function without this.
1171                  * But with imperfect damage info we may send pixels over USB
1172                  * that were, in fact, unchanged - wasting limited USB bandwidth
1173                  */
1174                 if (shadow)
1175                         new_back = vzalloc(new_len);
1176                 if (!new_back)
1177                         dev_info(info->dev,
1178                                  "No shadow/backing buffer allocated\n");
1179                 else {
1180                         vfree(dlfb->backing_buffer);
1181                         dlfb->backing_buffer = new_back;
1182                 }
1183         }
1184         return 0;
1185 }
1186
1187 /*
1188  * 1) Get EDID from hw, or use sw default
1189  * 2) Parse into various fb_info structs
1190  * 3) Allocate virtual framebuffer memory to back highest res mode
1191  *
1192  * Parses EDID into three places used by various parts of fbdev:
1193  * fb_var_screeninfo contains the timing of the monitor's preferred mode
1194  * fb_info.monspecs is full parsed EDID info, including monspecs.modedb
1195  * fb_info.modelist is a linked list of all monitor & VESA modes which work
1196  *
1197  * If EDID is not readable/valid, then modelist is all VESA modes,
1198  * monspecs is NULL, and fb_var_screeninfo is set to safe VESA mode
1199  * Returns 0 if successful
1200  */
1201 static int dlfb_setup_modes(struct dlfb_data *dlfb,
1202                            struct fb_info *info,
1203                            char *default_edid, size_t default_edid_size)
1204 {
1205         char *edid;
1206         int i, result = 0, tries = 3;
1207         struct device *dev = info->device;
1208         struct fb_videomode *mode;
1209         const struct fb_videomode *default_vmode = NULL;
1210
1211         if (info->dev) {
1212                 /* only use mutex if info has been registered */
1213                 mutex_lock(&info->lock);
1214                 /* parent device is used otherwise */
1215                 dev = info->dev;
1216         }
1217
1218         edid = kmalloc(EDID_LENGTH, GFP_KERNEL);
1219         if (!edid) {
1220                 result = -ENOMEM;
1221                 goto error;
1222         }
1223
1224         fb_destroy_modelist(&info->modelist);
1225         memset(&info->monspecs, 0, sizeof(info->monspecs));
1226
1227         /*
1228          * Try to (re)read EDID from hardware first
1229          * EDID data may return, but not parse as valid
1230          * Try again a few times, in case of e.g. analog cable noise
1231          */
1232         while (tries--) {
1233
1234                 i = dlfb_get_edid(dlfb, edid, EDID_LENGTH);
1235
1236                 if (i >= EDID_LENGTH)
1237                         fb_edid_to_monspecs(edid, &info->monspecs);
1238
1239                 if (info->monspecs.modedb_len > 0) {
1240                         dlfb->edid = edid;
1241                         dlfb->edid_size = i;
1242                         break;
1243                 }
1244         }
1245
1246         /* If that fails, use a previously returned EDID if available */
1247         if (info->monspecs.modedb_len == 0) {
1248                 dev_err(dev, "Unable to get valid EDID from device/display\n");
1249
1250                 if (dlfb->edid) {
1251                         fb_edid_to_monspecs(dlfb->edid, &info->monspecs);
1252                         if (info->monspecs.modedb_len > 0)
1253                                 dev_err(dev, "Using previously queried EDID\n");
1254                 }
1255         }
1256
1257         /* If that fails, use the default EDID we were handed */
1258         if (info->monspecs.modedb_len == 0) {
1259                 if (default_edid_size >= EDID_LENGTH) {
1260                         fb_edid_to_monspecs(default_edid, &info->monspecs);
1261                         if (info->monspecs.modedb_len > 0) {
1262                                 memcpy(edid, default_edid, default_edid_size);
1263                                 dlfb->edid = edid;
1264                                 dlfb->edid_size = default_edid_size;
1265                                 dev_err(dev, "Using default/backup EDID\n");
1266                         }
1267                 }
1268         }
1269
1270         /* If we've got modes, let's pick a best default mode */
1271         if (info->monspecs.modedb_len > 0) {
1272
1273                 for (i = 0; i < info->monspecs.modedb_len; i++) {
1274                         mode = &info->monspecs.modedb[i];
1275                         if (dlfb_is_valid_mode(mode, dlfb)) {
1276                                 fb_add_videomode(mode, &info->modelist);
1277                         } else {
1278                                 dev_dbg(dev, "Specified mode %dx%d too big\n",
1279                                         mode->xres, mode->yres);
1280                                 if (i == 0)
1281                                         /* if we've removed top/best mode */
1282                                         info->monspecs.misc
1283                                                 &= ~FB_MISC_1ST_DETAIL;
1284                         }
1285                 }
1286
1287                 default_vmode = fb_find_best_display(&info->monspecs,
1288                                                      &info->modelist);
1289         }
1290
1291         /* If everything else has failed, fall back to safe default mode */
1292         if (default_vmode == NULL) {
1293
1294                 struct fb_videomode fb_vmode = {0};
1295
1296                 /*
1297                  * Add the standard VESA modes to our modelist
1298                  * Since we don't have EDID, there may be modes that
1299                  * overspec monitor and/or are incorrect aspect ratio, etc.
1300                  * But at least the user has a chance to choose
1301                  */
1302                 for (i = 0; i < VESA_MODEDB_SIZE; i++) {
1303                         mode = (struct fb_videomode *)&vesa_modes[i];
1304                         if (dlfb_is_valid_mode(mode, dlfb))
1305                                 fb_add_videomode(mode, &info->modelist);
1306                         else
1307                                 dev_dbg(dev, "VESA mode %dx%d too big\n",
1308                                         mode->xres, mode->yres);
1309                 }
1310
1311                 /*
1312                  * default to resolution safe for projectors
1313                  * (since they are most common case without EDID)
1314                  */
1315                 fb_vmode.xres = 800;
1316                 fb_vmode.yres = 600;
1317                 fb_vmode.refresh = 60;
1318                 default_vmode = fb_find_nearest_mode(&fb_vmode,
1319                                                      &info->modelist);
1320         }
1321
1322         /* If we have good mode and no active clients*/
1323         if ((default_vmode != NULL) && (dlfb->fb_count == 0)) {
1324
1325                 fb_videomode_to_var(&info->var, default_vmode);
1326                 dlfb_var_color_format(&info->var);
1327
1328                 /*
1329                  * with mode size info, we can now alloc our framebuffer.
1330                  */
1331                 memcpy(&info->fix, &dlfb_fix, sizeof(dlfb_fix));
1332                 info->fix.line_length = info->var.xres *
1333                         (info->var.bits_per_pixel / 8);
1334
1335                 result = dlfb_realloc_framebuffer(dlfb, info);
1336
1337         } else
1338                 result = -EINVAL;
1339
1340 error:
1341         if (edid && (dlfb->edid != edid))
1342                 kfree(edid);
1343
1344         if (info->dev)
1345                 mutex_unlock(&info->lock);
1346
1347         return result;
1348 }
1349
1350 static ssize_t metrics_bytes_rendered_show(struct device *fbdev,
1351                                    struct device_attribute *a, char *buf) {
1352         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1353         struct dlfb_data *dlfb = fb_info->par;
1354         return snprintf(buf, PAGE_SIZE, "%u\n",
1355                         atomic_read(&dlfb->bytes_rendered));
1356 }
1357
1358 static ssize_t metrics_bytes_identical_show(struct device *fbdev,
1359                                    struct device_attribute *a, char *buf) {
1360         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1361         struct dlfb_data *dlfb = fb_info->par;
1362         return snprintf(buf, PAGE_SIZE, "%u\n",
1363                         atomic_read(&dlfb->bytes_identical));
1364 }
1365
1366 static ssize_t metrics_bytes_sent_show(struct device *fbdev,
1367                                    struct device_attribute *a, char *buf) {
1368         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1369         struct dlfb_data *dlfb = fb_info->par;
1370         return snprintf(buf, PAGE_SIZE, "%u\n",
1371                         atomic_read(&dlfb->bytes_sent));
1372 }
1373
1374 static ssize_t metrics_cpu_kcycles_used_show(struct device *fbdev,
1375                                    struct device_attribute *a, char *buf) {
1376         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1377         struct dlfb_data *dlfb = fb_info->par;
1378         return snprintf(buf, PAGE_SIZE, "%u\n",
1379                         atomic_read(&dlfb->cpu_kcycles_used));
1380 }
1381
1382 static ssize_t edid_show(
1383                         struct file *filp,
1384                         struct kobject *kobj, struct bin_attribute *a,
1385                          char *buf, loff_t off, size_t count) {
1386         struct device *fbdev = container_of(kobj, struct device, kobj);
1387         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1388         struct dlfb_data *dlfb = fb_info->par;
1389
1390         if (dlfb->edid == NULL)
1391                 return 0;
1392
1393         if ((off >= dlfb->edid_size) || (count > dlfb->edid_size))
1394                 return 0;
1395
1396         if (off + count > dlfb->edid_size)
1397                 count = dlfb->edid_size - off;
1398
1399         memcpy(buf, dlfb->edid, count);
1400
1401         return count;
1402 }
1403
1404 static ssize_t edid_store(
1405                         struct file *filp,
1406                         struct kobject *kobj, struct bin_attribute *a,
1407                         char *src, loff_t src_off, size_t src_size) {
1408         struct device *fbdev = container_of(kobj, struct device, kobj);
1409         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1410         struct dlfb_data *dlfb = fb_info->par;
1411         int ret;
1412
1413         /* We only support write of entire EDID at once, no offset*/
1414         if ((src_size != EDID_LENGTH) || (src_off != 0))
1415                 return -EINVAL;
1416
1417         ret = dlfb_setup_modes(dlfb, fb_info, src, src_size);
1418         if (ret)
1419                 return ret;
1420
1421         if (!dlfb->edid || memcmp(src, dlfb->edid, src_size))
1422                 return -EINVAL;
1423
1424         dlfb_ops_set_par(fb_info);
1425         return src_size;
1426 }
1427
1428 static ssize_t metrics_reset_store(struct device *fbdev,
1429                            struct device_attribute *attr,
1430                            const char *buf, size_t count)
1431 {
1432         struct fb_info *fb_info = dev_get_drvdata(fbdev);
1433         struct dlfb_data *dlfb = fb_info->par;
1434
1435         atomic_set(&dlfb->bytes_rendered, 0);
1436         atomic_set(&dlfb->bytes_identical, 0);
1437         atomic_set(&dlfb->bytes_sent, 0);
1438         atomic_set(&dlfb->cpu_kcycles_used, 0);
1439
1440         return count;
1441 }
1442
1443 static const struct bin_attribute edid_attr = {
1444         .attr.name = "edid",
1445         .attr.mode = 0666,
1446         .size = EDID_LENGTH,
1447         .read = edid_show,
1448         .write = edid_store
1449 };
1450
1451 static const struct device_attribute fb_device_attrs[] = {
1452         __ATTR_RO(metrics_bytes_rendered),
1453         __ATTR_RO(metrics_bytes_identical),
1454         __ATTR_RO(metrics_bytes_sent),
1455         __ATTR_RO(metrics_cpu_kcycles_used),
1456         __ATTR(metrics_reset, S_IWUSR, NULL, metrics_reset_store),
1457 };
1458
1459 /*
1460  * This is necessary before we can communicate with the display controller.
1461  */
1462 static int dlfb_select_std_channel(struct dlfb_data *dlfb)
1463 {
1464         int ret;
1465         void *buf;
1466         static const u8 set_def_chn[] = {
1467                                 0x57, 0xCD, 0xDC, 0xA7,
1468                                 0x1C, 0x88, 0x5E, 0x15,
1469                                 0x60, 0xFE, 0xC6, 0x97,
1470                                 0x16, 0x3D, 0x47, 0xF2  };
1471
1472         buf = kmemdup(set_def_chn, sizeof(set_def_chn), GFP_KERNEL);
1473
1474         if (!buf)
1475                 return -ENOMEM;
1476
1477         ret = usb_control_msg(dlfb->udev, usb_sndctrlpipe(dlfb->udev, 0),
1478                         NR_USB_REQUEST_CHANNEL,
1479                         (USB_DIR_OUT | USB_TYPE_VENDOR), 0, 0,
1480                         buf, sizeof(set_def_chn), USB_CTRL_SET_TIMEOUT);
1481
1482         kfree(buf);
1483
1484         return ret;
1485 }
1486
1487 static int dlfb_parse_vendor_descriptor(struct dlfb_data *dlfb,
1488                                         struct usb_interface *intf)
1489 {
1490         char *desc;
1491         char *buf;
1492         char *desc_end;
1493         int total_len;
1494
1495         buf = kzalloc(MAX_VENDOR_DESCRIPTOR_SIZE, GFP_KERNEL);
1496         if (!buf)
1497                 return false;
1498         desc = buf;
1499
1500         total_len = usb_get_descriptor(interface_to_usbdev(intf),
1501                                         0x5f, /* vendor specific */
1502                                         0, desc, MAX_VENDOR_DESCRIPTOR_SIZE);
1503
1504         /* if not found, look in configuration descriptor */
1505         if (total_len < 0) {
1506                 if (0 == usb_get_extra_descriptor(intf->cur_altsetting,
1507                         0x5f, &desc))
1508                         total_len = (int) desc[0];
1509         }
1510
1511         if (total_len > 5) {
1512                 dev_info(&intf->dev,
1513                          "vendor descriptor length: %d data: %11ph\n",
1514                          total_len, desc);
1515
1516                 if ((desc[0] != total_len) || /* descriptor length */
1517                     (desc[1] != 0x5f) ||   /* vendor descriptor type */
1518                     (desc[2] != 0x01) ||   /* version (2 bytes) */
1519                     (desc[3] != 0x00) ||
1520                     (desc[4] != total_len - 2)) /* length after type */
1521                         goto unrecognized;
1522
1523                 desc_end = desc + total_len;
1524                 desc += 5; /* the fixed header we've already parsed */
1525
1526                 while (desc < desc_end) {
1527                         u8 length;
1528                         u16 key;
1529
1530                         key = *desc++;
1531                         key |= (u16)*desc++ << 8;
1532                         length = *desc++;
1533
1534                         switch (key) {
1535                         case 0x0200: { /* max_area */
1536                                 u32 max_area = *desc++;
1537                                 max_area |= (u32)*desc++ << 8;
1538                                 max_area |= (u32)*desc++ << 16;
1539                                 max_area |= (u32)*desc++ << 24;
1540                                 dev_warn(&intf->dev,
1541                                          "DL chip limited to %d pixel modes\n",
1542                                          max_area);
1543                                 dlfb->sku_pixel_limit = max_area;
1544                                 break;
1545                         }
1546                         default:
1547                                 break;
1548                         }
1549                         desc += length;
1550                 }
1551         } else {
1552                 dev_info(&intf->dev, "vendor descriptor not available (%d)\n",
1553                          total_len);
1554         }
1555
1556         goto success;
1557
1558 unrecognized:
1559         /* allow udlfb to load for now even if firmware unrecognized */
1560         dev_err(&intf->dev, "Unrecognized vendor firmware descriptor\n");
1561
1562 success:
1563         kfree(buf);
1564         return true;
1565 }
1566
1567 static void dlfb_init_framebuffer_work(struct work_struct *work);
1568
1569 static int dlfb_usb_probe(struct usb_interface *intf,
1570                           const struct usb_device_id *id)
1571 {
1572         struct dlfb_data *dlfb;
1573         int retval = -ENOMEM;
1574         struct usb_device *usbdev = interface_to_usbdev(intf);
1575
1576         /* usb initialization */
1577         dlfb = kzalloc(sizeof(*dlfb), GFP_KERNEL);
1578         if (!dlfb) {
1579                 dev_err(&intf->dev, "%s: failed to allocate dlfb\n", __func__);
1580                 goto error;
1581         }
1582
1583         kref_init(&dlfb->kref); /* matching kref_put in usb .disconnect fn */
1584
1585         dlfb->udev = usbdev;
1586         usb_set_intfdata(intf, dlfb);
1587
1588         dev_dbg(&intf->dev, "console enable=%d\n", console);
1589         dev_dbg(&intf->dev, "fb_defio enable=%d\n", fb_defio);
1590         dev_dbg(&intf->dev, "shadow enable=%d\n", shadow);
1591
1592         dlfb->sku_pixel_limit = 2048 * 1152; /* default to maximum */
1593
1594         if (!dlfb_parse_vendor_descriptor(dlfb, intf)) {
1595                 dev_err(&intf->dev,
1596                         "firmware not recognized, incompatible device?\n");
1597                 goto error;
1598         }
1599
1600         if (pixel_limit) {
1601                 dev_warn(&intf->dev,
1602                          "DL chip limit of %d overridden to %d\n",
1603                          dlfb->sku_pixel_limit, pixel_limit);
1604                 dlfb->sku_pixel_limit = pixel_limit;
1605         }
1606
1607
1608         if (!dlfb_alloc_urb_list(dlfb, WRITES_IN_FLIGHT, MAX_TRANSFER)) {
1609                 retval = -ENOMEM;
1610                 dev_err(&intf->dev, "unable to allocate urb list\n");
1611                 goto error;
1612         }
1613
1614         kref_get(&dlfb->kref); /* matching kref_put in free_framebuffer_work */
1615
1616         /* We don't register a new USB class. Our client interface is dlfbev */
1617
1618         /* Workitem keep things fast & simple during USB enumeration */
1619         INIT_DELAYED_WORK(&dlfb->init_framebuffer_work,
1620                           dlfb_init_framebuffer_work);
1621         schedule_delayed_work(&dlfb->init_framebuffer_work, 0);
1622
1623         return 0;
1624
1625 error:
1626         if (dlfb) {
1627
1628                 kref_put(&dlfb->kref, dlfb_free); /* last ref from kref_init */
1629
1630                 /* dev has been deallocated. Do not dereference */
1631         }
1632
1633         return retval;
1634 }
1635
1636 static void dlfb_init_framebuffer_work(struct work_struct *work)
1637 {
1638         int i, retval;
1639         struct fb_info *info;
1640         const struct device_attribute *attr;
1641         struct dlfb_data *dlfb = container_of(work, struct dlfb_data,
1642                                              init_framebuffer_work.work);
1643
1644         /* allocates framebuffer driver structure, not framebuffer memory */
1645         info = framebuffer_alloc(0, &dlfb->udev->dev);
1646         if (!info) {
1647                 dev_err(&dlfb->udev->dev, "framebuffer_alloc failed\n");
1648                 goto error;
1649         }
1650
1651         dlfb->info = info;
1652         info->par = dlfb;
1653         info->pseudo_palette = dlfb->pseudo_palette;
1654         info->fbops = &dlfb_ops;
1655
1656         retval = fb_alloc_cmap(&info->cmap, 256, 0);
1657         if (retval < 0) {
1658                 dev_err(info->device, "cmap allocation failed: %d\n", retval);
1659                 goto error;
1660         }
1661
1662         INIT_DELAYED_WORK(&dlfb->free_framebuffer_work,
1663                           dlfb_free_framebuffer_work);
1664
1665         INIT_LIST_HEAD(&info->modelist);
1666
1667         retval = dlfb_setup_modes(dlfb, info, NULL, 0);
1668         if (retval != 0) {
1669                 dev_err(info->device,
1670                         "unable to find common mode for display and adapter\n");
1671                 goto error;
1672         }
1673
1674         /* ready to begin using device */
1675
1676         atomic_set(&dlfb->usb_active, 1);
1677         dlfb_select_std_channel(dlfb);
1678
1679         dlfb_ops_check_var(&info->var, info);
1680         dlfb_ops_set_par(info);
1681
1682         retval = register_framebuffer(info);
1683         if (retval < 0) {
1684                 dev_err(info->device, "unable to register framebuffer: %d\n",
1685                         retval);
1686                 goto error;
1687         }
1688
1689         for (i = 0; i < ARRAY_SIZE(fb_device_attrs); i++) {
1690                 attr = &fb_device_attrs[i];
1691                 retval = device_create_file(info->dev, attr);
1692                 if (retval)
1693                         dev_warn(info->device,
1694                                  "failed to create '%s' attribute: %d\n",
1695                                  attr->attr.name, retval);
1696         }
1697
1698         retval = device_create_bin_file(info->dev, &edid_attr);
1699         if (retval)
1700                 dev_warn(info->device, "failed to create '%s' attribute: %d\n",
1701                          edid_attr.attr.name, retval);
1702
1703         dev_info(info->device,
1704                  "%s is DisplayLink USB device (%dx%d, %dK framebuffer memory)\n",
1705                  dev_name(info->dev), info->var.xres, info->var.yres,
1706                  ((dlfb->backing_buffer) ?
1707                  info->fix.smem_len * 2 : info->fix.smem_len) >> 10);
1708         return;
1709
1710 error:
1711         dlfb_free_framebuffer(dlfb);
1712 }
1713
1714 static void dlfb_usb_disconnect(struct usb_interface *intf)
1715 {
1716         struct dlfb_data *dlfb;
1717         struct fb_info *info;
1718         int i;
1719
1720         dlfb = usb_get_intfdata(intf);
1721         info = dlfb->info;
1722
1723         dev_dbg(&intf->dev, "USB disconnect starting\n");
1724
1725         /* we virtualize until all fb clients release. Then we free */
1726         dlfb->virtualized = true;
1727
1728         /* When non-active we'll update virtual framebuffer, but no new urbs */
1729         atomic_set(&dlfb->usb_active, 0);
1730
1731         /* this function will wait for all in-flight urbs to complete */
1732         dlfb_free_urb_list(dlfb);
1733
1734         if (info) {
1735                 /* remove udlfb's sysfs interfaces */
1736                 for (i = 0; i < ARRAY_SIZE(fb_device_attrs); i++)
1737                         device_remove_file(info->dev, &fb_device_attrs[i]);
1738                 device_remove_bin_file(info->dev, &edid_attr);
1739                 unlink_framebuffer(info);
1740         }
1741
1742         usb_set_intfdata(intf, NULL);
1743         dlfb->udev = NULL;
1744
1745         /* if clients still have us open, will be freed on last close */
1746         if (dlfb->fb_count == 0)
1747                 schedule_delayed_work(&dlfb->free_framebuffer_work, 0);
1748
1749         /* release reference taken by kref_init in probe() */
1750         kref_put(&dlfb->kref, dlfb_free);
1751
1752         /* consider dlfb_data freed */
1753 }
1754
1755 static struct usb_driver dlfb_driver = {
1756         .name = "udlfb",
1757         .probe = dlfb_usb_probe,
1758         .disconnect = dlfb_usb_disconnect,
1759         .id_table = id_table,
1760 };
1761
1762 module_usb_driver(dlfb_driver);
1763
1764 static void dlfb_urb_completion(struct urb *urb)
1765 {
1766         struct urb_node *unode = urb->context;
1767         struct dlfb_data *dlfb = unode->dlfb;
1768         unsigned long flags;
1769
1770         switch (urb->status) {
1771         case 0:
1772                 /* success */
1773                 break;
1774         case -ECONNRESET:
1775         case -ENOENT:
1776         case -ESHUTDOWN:
1777                 /* sync/async unlink faults aren't errors */
1778                 break;
1779         default:
1780                 dev_err(&dlfb->udev->dev,
1781                         "%s - nonzero write bulk status received: %d\n",
1782                         __func__, urb->status);
1783                 atomic_set(&dlfb->lost_pixels, 1);
1784                 break;
1785         }
1786
1787         urb->transfer_buffer_length = dlfb->urbs.size; /* reset to actual */
1788
1789         spin_lock_irqsave(&dlfb->urbs.lock, flags);
1790         list_add_tail(&unode->entry, &dlfb->urbs.list);
1791         dlfb->urbs.available++;
1792         spin_unlock_irqrestore(&dlfb->urbs.lock, flags);
1793
1794         up(&dlfb->urbs.limit_sem);
1795 }
1796
1797 static void dlfb_free_urb_list(struct dlfb_data *dlfb)
1798 {
1799         int count = dlfb->urbs.count;
1800         struct list_head *node;
1801         struct urb_node *unode;
1802         struct urb *urb;
1803         unsigned long flags;
1804
1805         /* keep waiting and freeing, until we've got 'em all */
1806         while (count--) {
1807                 down(&dlfb->urbs.limit_sem);
1808
1809                 spin_lock_irqsave(&dlfb->urbs.lock, flags);
1810
1811                 node = dlfb->urbs.list.next; /* have reserved one with sem */
1812                 list_del_init(node);
1813
1814                 spin_unlock_irqrestore(&dlfb->urbs.lock, flags);
1815
1816                 unode = list_entry(node, struct urb_node, entry);
1817                 urb = unode->urb;
1818
1819                 /* Free each separately allocated piece */
1820                 usb_free_coherent(urb->dev, dlfb->urbs.size,
1821                                   urb->transfer_buffer, urb->transfer_dma);
1822                 usb_free_urb(urb);
1823                 kfree(node);
1824         }
1825
1826         dlfb->urbs.count = 0;
1827 }
1828
1829 static int dlfb_alloc_urb_list(struct dlfb_data *dlfb, int count, size_t size)
1830 {
1831         int i = 0;
1832         struct urb *urb;
1833         struct urb_node *unode;
1834         char *buf;
1835
1836         spin_lock_init(&dlfb->urbs.lock);
1837
1838         dlfb->urbs.size = size;
1839         INIT_LIST_HEAD(&dlfb->urbs.list);
1840
1841         while (i < count) {
1842                 unode = kzalloc(sizeof(*unode), GFP_KERNEL);
1843                 if (!unode)
1844                         break;
1845                 unode->dlfb = dlfb;
1846
1847                 urb = usb_alloc_urb(0, GFP_KERNEL);
1848                 if (!urb) {
1849                         kfree(unode);
1850                         break;
1851                 }
1852                 unode->urb = urb;
1853
1854                 buf = usb_alloc_coherent(dlfb->udev, MAX_TRANSFER, GFP_KERNEL,
1855                                          &urb->transfer_dma);
1856                 if (!buf) {
1857                         kfree(unode);
1858                         usb_free_urb(urb);
1859                         break;
1860                 }
1861
1862                 /* urb->transfer_buffer_length set to actual before submit */
1863                 usb_fill_bulk_urb(urb, dlfb->udev, usb_sndbulkpipe(dlfb->udev, 1),
1864                         buf, size, dlfb_urb_completion, unode);
1865                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1866
1867                 list_add_tail(&unode->entry, &dlfb->urbs.list);
1868
1869                 i++;
1870         }
1871
1872         sema_init(&dlfb->urbs.limit_sem, i);
1873         dlfb->urbs.count = i;
1874         dlfb->urbs.available = i;
1875
1876         return i;
1877 }
1878
1879 static struct urb *dlfb_get_urb(struct dlfb_data *dlfb)
1880 {
1881         int ret;
1882         struct list_head *entry;
1883         struct urb_node *unode;
1884         unsigned long flags;
1885
1886         /* Wait for an in-flight buffer to complete and get re-queued */
1887         ret = down_timeout(&dlfb->urbs.limit_sem, GET_URB_TIMEOUT);
1888         if (ret) {
1889                 atomic_set(&dlfb->lost_pixels, 1);
1890                 dev_warn(&dlfb->udev->dev,
1891                          "wait for urb interrupted: %d available: %d\n",
1892                          ret, dlfb->urbs.available);
1893                 return NULL;
1894         }
1895
1896         spin_lock_irqsave(&dlfb->urbs.lock, flags);
1897
1898         BUG_ON(list_empty(&dlfb->urbs.list)); /* reserved one with limit_sem */
1899         entry = dlfb->urbs.list.next;
1900         list_del_init(entry);
1901         dlfb->urbs.available--;
1902
1903         spin_unlock_irqrestore(&dlfb->urbs.lock, flags);
1904
1905         unode = list_entry(entry, struct urb_node, entry);
1906         return unode->urb;
1907 }
1908
1909 static int dlfb_submit_urb(struct dlfb_data *dlfb, struct urb *urb, size_t len)
1910 {
1911         int ret;
1912
1913         BUG_ON(len > dlfb->urbs.size);
1914
1915         urb->transfer_buffer_length = len; /* set to actual payload len */
1916         ret = usb_submit_urb(urb, GFP_KERNEL);
1917         if (ret) {
1918                 dlfb_urb_completion(urb); /* because no one else will */
1919                 atomic_set(&dlfb->lost_pixels, 1);
1920                 dev_err(&dlfb->udev->dev, "submit urb error: %d\n", ret);
1921         }
1922         return ret;
1923 }
1924
1925 module_param(console, bool, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
1926 MODULE_PARM_DESC(console, "Allow fbcon to open framebuffer");
1927
1928 module_param(fb_defio, bool, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
1929 MODULE_PARM_DESC(fb_defio, "Page fault detection of mmap writes");
1930
1931 module_param(shadow, bool, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
1932 MODULE_PARM_DESC(shadow, "Shadow vid mem. Disable to save mem but lose perf");
1933
1934 module_param(pixel_limit, int, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
1935 MODULE_PARM_DESC(pixel_limit, "Force limit on max mode (in x*y pixels)");
1936
1937 MODULE_AUTHOR("Roberto De Ioris <roberto@unbit.it>, "
1938               "Jaya Kumar <jayakumar.lkml@gmail.com>, "
1939               "Bernie Thompson <bernie@plugable.com>");
1940 MODULE_DESCRIPTION("DisplayLink kernel framebuffer driver");
1941 MODULE_LICENSE("GPL");
1942