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