OSDN Git Service

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