OSDN Git Service

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