GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / gpu / drm / tinydrm / mipi-dbi.c
1 /*
2  * MIPI Display Bus Interface (DBI) LCD controller support
3  *
4  * Copyright 2016 Noralf Trønnes
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  */
11
12 #include <drm/drm_gem_framebuffer_helper.h>
13 #include <drm/tinydrm/mipi-dbi.h>
14 #include <drm/tinydrm/tinydrm-helpers.h>
15 #include <linux/debugfs.h>
16 #include <linux/dma-buf.h>
17 #include <linux/gpio/consumer.h>
18 #include <linux/module.h>
19 #include <linux/regulator/consumer.h>
20 #include <linux/spi/spi.h>
21 #include <video/mipi_display.h>
22
23 #define MIPI_DBI_MAX_SPI_READ_SPEED 2000000 /* 2MHz */
24
25 #define DCS_POWER_MODE_DISPLAY                  BIT(2)
26 #define DCS_POWER_MODE_DISPLAY_NORMAL_MODE      BIT(3)
27 #define DCS_POWER_MODE_SLEEP_MODE               BIT(4)
28 #define DCS_POWER_MODE_PARTIAL_MODE             BIT(5)
29 #define DCS_POWER_MODE_IDLE_MODE                BIT(6)
30 #define DCS_POWER_MODE_RESERVED_MASK            (BIT(0) | BIT(1) | BIT(7))
31
32 /**
33  * DOC: overview
34  *
35  * This library provides helpers for MIPI Display Bus Interface (DBI)
36  * compatible display controllers.
37  *
38  * Many controllers for tiny lcd displays are MIPI compliant and can use this
39  * library. If a controller uses registers 0x2A and 0x2B to set the area to
40  * update and uses register 0x2C to write to frame memory, it is most likely
41  * MIPI compliant.
42  *
43  * Only MIPI Type 1 displays are supported since a full frame memory is needed.
44  *
45  * There are 3 MIPI DBI implementation types:
46  *
47  * A. Motorola 6800 type parallel bus
48  *
49  * B. Intel 8080 type parallel bus
50  *
51  * C. SPI type with 3 options:
52  *
53  *    1. 9-bit with the Data/Command signal as the ninth bit
54  *    2. Same as above except it's sent as 16 bits
55  *    3. 8-bit with the Data/Command signal as a separate D/CX pin
56  *
57  * Currently mipi_dbi only supports Type C options 1 and 3 with
58  * mipi_dbi_spi_init().
59  */
60
61 #define MIPI_DBI_DEBUG_COMMAND(cmd, data, len) \
62 ({ \
63         if (!len) \
64                 DRM_DEBUG_DRIVER("cmd=%02x\n", cmd); \
65         else if (len <= 32) \
66                 DRM_DEBUG_DRIVER("cmd=%02x, par=%*ph\n", cmd, (int)len, data);\
67         else \
68                 DRM_DEBUG_DRIVER("cmd=%02x, len=%zu\n", cmd, len); \
69 })
70
71 static const u8 mipi_dbi_dcs_read_commands[] = {
72         MIPI_DCS_GET_DISPLAY_ID,
73         MIPI_DCS_GET_RED_CHANNEL,
74         MIPI_DCS_GET_GREEN_CHANNEL,
75         MIPI_DCS_GET_BLUE_CHANNEL,
76         MIPI_DCS_GET_DISPLAY_STATUS,
77         MIPI_DCS_GET_POWER_MODE,
78         MIPI_DCS_GET_ADDRESS_MODE,
79         MIPI_DCS_GET_PIXEL_FORMAT,
80         MIPI_DCS_GET_DISPLAY_MODE,
81         MIPI_DCS_GET_SIGNAL_MODE,
82         MIPI_DCS_GET_DIAGNOSTIC_RESULT,
83         MIPI_DCS_READ_MEMORY_START,
84         MIPI_DCS_READ_MEMORY_CONTINUE,
85         MIPI_DCS_GET_SCANLINE,
86         MIPI_DCS_GET_DISPLAY_BRIGHTNESS,
87         MIPI_DCS_GET_CONTROL_DISPLAY,
88         MIPI_DCS_GET_POWER_SAVE,
89         MIPI_DCS_GET_CABC_MIN_BRIGHTNESS,
90         MIPI_DCS_READ_DDB_START,
91         MIPI_DCS_READ_DDB_CONTINUE,
92         0, /* sentinel */
93 };
94
95 static bool mipi_dbi_command_is_read(struct mipi_dbi *mipi, u8 cmd)
96 {
97         unsigned int i;
98
99         if (!mipi->read_commands)
100                 return false;
101
102         for (i = 0; i < 0xff; i++) {
103                 if (!mipi->read_commands[i])
104                         return false;
105                 if (cmd == mipi->read_commands[i])
106                         return true;
107         }
108
109         return false;
110 }
111
112 /**
113  * mipi_dbi_command_read - MIPI DCS read command
114  * @mipi: MIPI structure
115  * @cmd: Command
116  * @val: Value read
117  *
118  * Send MIPI DCS read command to the controller.
119  *
120  * Returns:
121  * Zero on success, negative error code on failure.
122  */
123 int mipi_dbi_command_read(struct mipi_dbi *mipi, u8 cmd, u8 *val)
124 {
125         if (!mipi->read_commands)
126                 return -EACCES;
127
128         if (!mipi_dbi_command_is_read(mipi, cmd))
129                 return -EINVAL;
130
131         return mipi_dbi_command_buf(mipi, cmd, val, 1);
132 }
133 EXPORT_SYMBOL(mipi_dbi_command_read);
134
135 /**
136  * mipi_dbi_command_buf - MIPI DCS command with parameter(s) in an array
137  * @mipi: MIPI structure
138  * @cmd: Command
139  * @data: Parameter buffer
140  * @len: Buffer length
141  *
142  * Returns:
143  * Zero on success, negative error code on failure.
144  */
145 int mipi_dbi_command_buf(struct mipi_dbi *mipi, u8 cmd, u8 *data, size_t len)
146 {
147         u8 *cmdbuf;
148         int ret;
149
150         /* SPI requires dma-safe buffers */
151         cmdbuf = kmemdup(&cmd, 1, GFP_KERNEL);
152         if (!cmdbuf)
153                 return -ENOMEM;
154
155         mutex_lock(&mipi->cmdlock);
156         ret = mipi->command(mipi, cmdbuf, data, len);
157         mutex_unlock(&mipi->cmdlock);
158
159         kfree(cmdbuf);
160
161         return ret;
162 }
163 EXPORT_SYMBOL(mipi_dbi_command_buf);
164
165 /* This should only be used by mipi_dbi_command() */
166 int mipi_dbi_command_stackbuf(struct mipi_dbi *mipi, u8 cmd, u8 *data, size_t len)
167 {
168         u8 *buf;
169         int ret;
170
171         buf = kmemdup(data, len, GFP_KERNEL);
172         if (!buf)
173                 return -ENOMEM;
174
175         ret = mipi_dbi_command_buf(mipi, cmd, buf, len);
176
177         kfree(buf);
178
179         return ret;
180 }
181 EXPORT_SYMBOL(mipi_dbi_command_stackbuf);
182
183 /**
184  * mipi_dbi_buf_copy - Copy a framebuffer, transforming it if necessary
185  * @dst: The destination buffer
186  * @fb: The source framebuffer
187  * @clip: Clipping rectangle of the area to be copied
188  * @swap: When true, swap MSB/LSB of 16-bit values
189  *
190  * Returns:
191  * Zero on success, negative error code on failure.
192  */
193 int mipi_dbi_buf_copy(void *dst, struct drm_framebuffer *fb,
194                       struct drm_clip_rect *clip, bool swap)
195 {
196         struct drm_gem_cma_object *cma_obj = drm_fb_cma_get_gem_obj(fb, 0);
197         struct dma_buf_attachment *import_attach = cma_obj->base.import_attach;
198         struct drm_format_name_buf format_name;
199         void *src = cma_obj->vaddr;
200         int ret = 0;
201
202         if (import_attach) {
203                 ret = dma_buf_begin_cpu_access(import_attach->dmabuf,
204                                                DMA_FROM_DEVICE);
205                 if (ret)
206                         return ret;
207         }
208
209         switch (fb->format->format) {
210         case DRM_FORMAT_RGB565:
211                 if (swap)
212                         tinydrm_swab16(dst, src, fb, clip);
213                 else
214                         tinydrm_memcpy(dst, src, fb, clip);
215                 break;
216         case DRM_FORMAT_XRGB8888:
217                 tinydrm_xrgb8888_to_rgb565(dst, src, fb, clip, swap);
218                 break;
219         default:
220                 dev_err_once(fb->dev->dev, "Format is not supported: %s\n",
221                              drm_get_format_name(fb->format->format,
222                                                  &format_name));
223                 return -EINVAL;
224         }
225
226         if (import_attach)
227                 ret = dma_buf_end_cpu_access(import_attach->dmabuf,
228                                              DMA_FROM_DEVICE);
229         return ret;
230 }
231 EXPORT_SYMBOL(mipi_dbi_buf_copy);
232
233 static int mipi_dbi_fb_dirty(struct drm_framebuffer *fb,
234                              struct drm_file *file_priv,
235                              unsigned int flags, unsigned int color,
236                              struct drm_clip_rect *clips,
237                              unsigned int num_clips)
238 {
239         struct drm_gem_cma_object *cma_obj = drm_fb_cma_get_gem_obj(fb, 0);
240         struct tinydrm_device *tdev = fb->dev->dev_private;
241         struct mipi_dbi *mipi = mipi_dbi_from_tinydrm(tdev);
242         bool swap = mipi->swap_bytes;
243         struct drm_clip_rect clip;
244         int ret = 0;
245         bool full;
246         void *tr;
247
248         if (!mipi->enabled)
249                 return 0;
250
251         full = tinydrm_merge_clips(&clip, clips, num_clips, flags,
252                                    fb->width, fb->height);
253
254         DRM_DEBUG("Flushing [FB:%d] x1=%u, x2=%u, y1=%u, y2=%u\n", fb->base.id,
255                   clip.x1, clip.x2, clip.y1, clip.y2);
256
257         if (!mipi->dc || !full || swap ||
258             fb->format->format == DRM_FORMAT_XRGB8888) {
259                 tr = mipi->tx_buf;
260                 ret = mipi_dbi_buf_copy(mipi->tx_buf, fb, &clip, swap);
261                 if (ret)
262                         return ret;
263         } else {
264                 tr = cma_obj->vaddr;
265         }
266
267         mipi_dbi_command(mipi, MIPI_DCS_SET_COLUMN_ADDRESS,
268                          (clip.x1 >> 8) & 0xFF, clip.x1 & 0xFF,
269                          (clip.x2 >> 8) & 0xFF, (clip.x2 - 1) & 0xFF);
270         mipi_dbi_command(mipi, MIPI_DCS_SET_PAGE_ADDRESS,
271                          (clip.y1 >> 8) & 0xFF, clip.y1 & 0xFF,
272                          (clip.y2 >> 8) & 0xFF, (clip.y2 - 1) & 0xFF);
273
274         ret = mipi_dbi_command_buf(mipi, MIPI_DCS_WRITE_MEMORY_START, tr,
275                                 (clip.x2 - clip.x1) * (clip.y2 - clip.y1) * 2);
276
277         return ret;
278 }
279
280 static const struct drm_framebuffer_funcs mipi_dbi_fb_funcs = {
281         .destroy        = drm_gem_fb_destroy,
282         .create_handle  = drm_gem_fb_create_handle,
283         .dirty          = tinydrm_fb_dirty,
284 };
285
286 /**
287  * mipi_dbi_enable_flush - MIPI DBI enable helper
288  * @mipi: MIPI DBI structure
289  * @crtc_state: CRTC state
290  * @plane_state: Plane state
291  *
292  * This function sets &mipi_dbi->enabled, flushes the whole framebuffer and
293  * enables the backlight. Drivers can use this in their
294  * &drm_simple_display_pipe_funcs->enable callback.
295  */
296 void mipi_dbi_enable_flush(struct mipi_dbi *mipi,
297                            struct drm_crtc_state *crtc_state,
298                            struct drm_plane_state *plane_state)
299 {
300         struct tinydrm_device *tdev = &mipi->tinydrm;
301         struct drm_framebuffer *fb = plane_state->fb;
302
303         mipi->enabled = true;
304         if (fb)
305                 tdev->fb_dirty(fb, NULL, 0, 0, NULL, 0);
306
307         backlight_enable(mipi->backlight);
308 }
309 EXPORT_SYMBOL(mipi_dbi_enable_flush);
310
311 static void mipi_dbi_blank(struct mipi_dbi *mipi)
312 {
313         struct drm_device *drm = mipi->tinydrm.drm;
314         u16 height = drm->mode_config.min_height;
315         u16 width = drm->mode_config.min_width;
316         size_t len = width * height * 2;
317
318         memset(mipi->tx_buf, 0, len);
319
320         mipi_dbi_command(mipi, MIPI_DCS_SET_COLUMN_ADDRESS, 0, 0,
321                          (width >> 8) & 0xFF, (width - 1) & 0xFF);
322         mipi_dbi_command(mipi, MIPI_DCS_SET_PAGE_ADDRESS, 0, 0,
323                          (height >> 8) & 0xFF, (height - 1) & 0xFF);
324         mipi_dbi_command_buf(mipi, MIPI_DCS_WRITE_MEMORY_START,
325                              (u8 *)mipi->tx_buf, len);
326 }
327
328 /**
329  * mipi_dbi_pipe_disable - MIPI DBI pipe disable helper
330  * @pipe: Display pipe
331  *
332  * This function disables backlight if present, if not the display memory is
333  * blanked. The regulator is disabled if in use. Drivers can use this as their
334  * &drm_simple_display_pipe_funcs->disable callback.
335  */
336 void mipi_dbi_pipe_disable(struct drm_simple_display_pipe *pipe)
337 {
338         struct tinydrm_device *tdev = pipe_to_tinydrm(pipe);
339         struct mipi_dbi *mipi = mipi_dbi_from_tinydrm(tdev);
340
341         DRM_DEBUG_KMS("\n");
342
343         mipi->enabled = false;
344
345         if (mipi->backlight)
346                 backlight_disable(mipi->backlight);
347         else
348                 mipi_dbi_blank(mipi);
349
350         if (mipi->regulator)
351                 regulator_disable(mipi->regulator);
352 }
353 EXPORT_SYMBOL(mipi_dbi_pipe_disable);
354
355 static const uint32_t mipi_dbi_formats[] = {
356         DRM_FORMAT_RGB565,
357         DRM_FORMAT_XRGB8888,
358 };
359
360 /**
361  * mipi_dbi_init - MIPI DBI initialization
362  * @dev: Parent device
363  * @mipi: &mipi_dbi structure to initialize
364  * @pipe_funcs: Display pipe functions
365  * @driver: DRM driver
366  * @mode: Display mode
367  * @rotation: Initial rotation in degrees Counter Clock Wise
368  *
369  * This function initializes a &mipi_dbi structure and it's underlying
370  * @tinydrm_device. It also sets up the display pipeline.
371  *
372  * Supported formats: Native RGB565 and emulated XRGB8888.
373  *
374  * Objects created by this function will be automatically freed on driver
375  * detach (devres).
376  *
377  * Returns:
378  * Zero on success, negative error code on failure.
379  */
380 int mipi_dbi_init(struct device *dev, struct mipi_dbi *mipi,
381                   const struct drm_simple_display_pipe_funcs *pipe_funcs,
382                   struct drm_driver *driver,
383                   const struct drm_display_mode *mode, unsigned int rotation)
384 {
385         size_t bufsize = mode->vdisplay * mode->hdisplay * sizeof(u16);
386         struct tinydrm_device *tdev = &mipi->tinydrm;
387         int ret;
388
389         if (!mipi->command)
390                 return -EINVAL;
391
392         mutex_init(&mipi->cmdlock);
393
394         mipi->tx_buf = devm_kmalloc(dev, bufsize, GFP_KERNEL);
395         if (!mipi->tx_buf)
396                 return -ENOMEM;
397
398         ret = devm_tinydrm_init(dev, tdev, &mipi_dbi_fb_funcs, driver);
399         if (ret)
400                 return ret;
401
402         tdev->fb_dirty = mipi_dbi_fb_dirty;
403
404         /* TODO: Maybe add DRM_MODE_CONNECTOR_SPI */
405         ret = tinydrm_display_pipe_init(tdev, pipe_funcs,
406                                         DRM_MODE_CONNECTOR_VIRTUAL,
407                                         mipi_dbi_formats,
408                                         ARRAY_SIZE(mipi_dbi_formats), mode,
409                                         rotation);
410         if (ret)
411                 return ret;
412
413         tdev->drm->mode_config.preferred_depth = 16;
414         mipi->rotation = rotation;
415
416         drm_mode_config_reset(tdev->drm);
417
418         DRM_DEBUG_KMS("preferred_depth=%u, rotation = %u\n",
419                       tdev->drm->mode_config.preferred_depth, rotation);
420
421         return 0;
422 }
423 EXPORT_SYMBOL(mipi_dbi_init);
424
425 /**
426  * mipi_dbi_hw_reset - Hardware reset of controller
427  * @mipi: MIPI DBI structure
428  *
429  * Reset controller if the &mipi_dbi->reset gpio is set.
430  */
431 void mipi_dbi_hw_reset(struct mipi_dbi *mipi)
432 {
433         if (!mipi->reset)
434                 return;
435
436         gpiod_set_value_cansleep(mipi->reset, 0);
437         usleep_range(20, 1000);
438         gpiod_set_value_cansleep(mipi->reset, 1);
439         msleep(120);
440 }
441 EXPORT_SYMBOL(mipi_dbi_hw_reset);
442
443 /**
444  * mipi_dbi_display_is_on - Check if display is on
445  * @mipi: MIPI DBI structure
446  *
447  * This function checks the Power Mode register (if readable) to see if
448  * display output is turned on. This can be used to see if the bootloader
449  * has already turned on the display avoiding flicker when the pipeline is
450  * enabled.
451  *
452  * Returns:
453  * true if the display can be verified to be on, false otherwise.
454  */
455 bool mipi_dbi_display_is_on(struct mipi_dbi *mipi)
456 {
457         u8 val;
458
459         if (mipi_dbi_command_read(mipi, MIPI_DCS_GET_POWER_MODE, &val))
460                 return false;
461
462         val &= ~DCS_POWER_MODE_RESERVED_MASK;
463
464         /* The poweron/reset value is 08h DCS_POWER_MODE_DISPLAY_NORMAL_MODE */
465         if (val != (DCS_POWER_MODE_DISPLAY |
466             DCS_POWER_MODE_DISPLAY_NORMAL_MODE | DCS_POWER_MODE_SLEEP_MODE))
467                 return false;
468
469         DRM_DEBUG_DRIVER("Display is ON\n");
470
471         return true;
472 }
473 EXPORT_SYMBOL(mipi_dbi_display_is_on);
474
475 static int mipi_dbi_poweron_reset_conditional(struct mipi_dbi *mipi, bool cond)
476 {
477         struct device *dev = mipi->tinydrm.drm->dev;
478         int ret;
479
480         if (mipi->regulator) {
481                 ret = regulator_enable(mipi->regulator);
482                 if (ret) {
483                         DRM_DEV_ERROR(dev, "Failed to enable regulator (%d)\n", ret);
484                         return ret;
485                 }
486         }
487
488         if (cond && mipi_dbi_display_is_on(mipi))
489                 return 1;
490
491         mipi_dbi_hw_reset(mipi);
492         ret = mipi_dbi_command(mipi, MIPI_DCS_SOFT_RESET);
493         if (ret) {
494                 DRM_DEV_ERROR(dev, "Failed to send reset command (%d)\n", ret);
495                 if (mipi->regulator)
496                         regulator_disable(mipi->regulator);
497                 return ret;
498         }
499
500         /*
501          * If we did a hw reset, we know the controller is in Sleep mode and
502          * per MIPI DSC spec should wait 5ms after soft reset. If we didn't,
503          * we assume worst case and wait 120ms.
504          */
505         if (mipi->reset)
506                 usleep_range(5000, 20000);
507         else
508                 msleep(120);
509
510         return 0;
511 }
512
513 /**
514  * mipi_dbi_poweron_reset - MIPI DBI poweron and reset
515  * @mipi: MIPI DBI structure
516  *
517  * This function enables the regulator if used and does a hardware and software
518  * reset.
519  *
520  * Returns:
521  * Zero on success, or a negative error code.
522  */
523 int mipi_dbi_poweron_reset(struct mipi_dbi *mipi)
524 {
525         return mipi_dbi_poweron_reset_conditional(mipi, false);
526 }
527 EXPORT_SYMBOL(mipi_dbi_poweron_reset);
528
529 /**
530  * mipi_dbi_poweron_conditional_reset - MIPI DBI poweron and conditional reset
531  * @mipi: MIPI DBI structure
532  *
533  * This function enables the regulator if used and if the display is off, it
534  * does a hardware and software reset. If mipi_dbi_display_is_on() determines
535  * that the display is on, no reset is performed.
536  *
537  * Returns:
538  * Zero if the controller was reset, 1 if the display was already on, or a
539  * negative error code.
540  */
541 int mipi_dbi_poweron_conditional_reset(struct mipi_dbi *mipi)
542 {
543         return mipi_dbi_poweron_reset_conditional(mipi, true);
544 }
545 EXPORT_SYMBOL(mipi_dbi_poweron_conditional_reset);
546
547 #if IS_ENABLED(CONFIG_SPI)
548
549 /**
550  * mipi_dbi_spi_cmd_max_speed - get the maximum SPI bus speed
551  * @spi: SPI device
552  * @len: The transfer buffer length.
553  *
554  * Many controllers have a max speed of 10MHz, but can be pushed way beyond
555  * that. Increase reliability by running pixel data at max speed and the rest
556  * at 10MHz, preventing transfer glitches from messing up the init settings.
557  */
558 u32 mipi_dbi_spi_cmd_max_speed(struct spi_device *spi, size_t len)
559 {
560         if (len > 64)
561                 return 0; /* use default */
562
563         return min_t(u32, 10000000, spi->max_speed_hz);
564 }
565 EXPORT_SYMBOL(mipi_dbi_spi_cmd_max_speed);
566
567 /*
568  * MIPI DBI Type C Option 1
569  *
570  * If the SPI controller doesn't have 9 bits per word support,
571  * use blocks of 9 bytes to send 8x 9-bit words using a 8-bit SPI transfer.
572  * Pad partial blocks with MIPI_DCS_NOP (zero).
573  * This is how the D/C bit (x) is added:
574  *     x7654321
575  *     0x765432
576  *     10x76543
577  *     210x7654
578  *     3210x765
579  *     43210x76
580  *     543210x7
581  *     6543210x
582  *     76543210
583  */
584
585 static int mipi_dbi_spi1e_transfer(struct mipi_dbi *mipi, int dc,
586                                    const void *buf, size_t len,
587                                    unsigned int bpw)
588 {
589         bool swap_bytes = (bpw == 16 && tinydrm_machine_little_endian());
590         size_t chunk, max_chunk = mipi->tx_buf9_len;
591         struct spi_device *spi = mipi->spi;
592         struct spi_transfer tr = {
593                 .tx_buf = mipi->tx_buf9,
594                 .bits_per_word = 8,
595         };
596         struct spi_message m;
597         const u8 *src = buf;
598         int i, ret;
599         u8 *dst;
600
601         if (drm_debug & DRM_UT_DRIVER)
602                 pr_debug("[drm:%s] dc=%d, max_chunk=%zu, transfers:\n",
603                          __func__, dc, max_chunk);
604
605         tr.speed_hz = mipi_dbi_spi_cmd_max_speed(spi, len);
606         spi_message_init_with_transfers(&m, &tr, 1);
607
608         if (!dc) {
609                 if (WARN_ON_ONCE(len != 1))
610                         return -EINVAL;
611
612                 /* Command: pad no-op's (zeroes) at beginning of block */
613                 dst = mipi->tx_buf9;
614                 memset(dst, 0, 9);
615                 dst[8] = *src;
616                 tr.len = 9;
617
618                 tinydrm_dbg_spi_message(spi, &m);
619
620                 return spi_sync(spi, &m);
621         }
622
623         /* max with room for adding one bit per byte */
624         max_chunk = max_chunk / 9 * 8;
625         /* but no bigger than len */
626         max_chunk = min(max_chunk, len);
627         /* 8 byte blocks */
628         max_chunk = max_t(size_t, 8, max_chunk & ~0x7);
629
630         while (len) {
631                 size_t added = 0;
632
633                 chunk = min(len, max_chunk);
634                 len -= chunk;
635                 dst = mipi->tx_buf9;
636
637                 if (chunk < 8) {
638                         u8 val, carry = 0;
639
640                         /* Data: pad no-op's (zeroes) at end of block */
641                         memset(dst, 0, 9);
642
643                         if (swap_bytes) {
644                                 for (i = 1; i < (chunk + 1); i++) {
645                                         val = src[1];
646                                         *dst++ = carry | BIT(8 - i) | (val >> i);
647                                         carry = val << (8 - i);
648                                         i++;
649                                         val = src[0];
650                                         *dst++ = carry | BIT(8 - i) | (val >> i);
651                                         carry = val << (8 - i);
652                                         src += 2;
653                                 }
654                                 *dst++ = carry;
655                         } else {
656                                 for (i = 1; i < (chunk + 1); i++) {
657                                         val = *src++;
658                                         *dst++ = carry | BIT(8 - i) | (val >> i);
659                                         carry = val << (8 - i);
660                                 }
661                                 *dst++ = carry;
662                         }
663
664                         chunk = 8;
665                         added = 1;
666                 } else {
667                         for (i = 0; i < chunk; i += 8) {
668                                 if (swap_bytes) {
669                                         *dst++ =                 BIT(7) | (src[1] >> 1);
670                                         *dst++ = (src[1] << 7) | BIT(6) | (src[0] >> 2);
671                                         *dst++ = (src[0] << 6) | BIT(5) | (src[3] >> 3);
672                                         *dst++ = (src[3] << 5) | BIT(4) | (src[2] >> 4);
673                                         *dst++ = (src[2] << 4) | BIT(3) | (src[5] >> 5);
674                                         *dst++ = (src[5] << 3) | BIT(2) | (src[4] >> 6);
675                                         *dst++ = (src[4] << 2) | BIT(1) | (src[7] >> 7);
676                                         *dst++ = (src[7] << 1) | BIT(0);
677                                         *dst++ = src[6];
678                                 } else {
679                                         *dst++ =                 BIT(7) | (src[0] >> 1);
680                                         *dst++ = (src[0] << 7) | BIT(6) | (src[1] >> 2);
681                                         *dst++ = (src[1] << 6) | BIT(5) | (src[2] >> 3);
682                                         *dst++ = (src[2] << 5) | BIT(4) | (src[3] >> 4);
683                                         *dst++ = (src[3] << 4) | BIT(3) | (src[4] >> 5);
684                                         *dst++ = (src[4] << 3) | BIT(2) | (src[5] >> 6);
685                                         *dst++ = (src[5] << 2) | BIT(1) | (src[6] >> 7);
686                                         *dst++ = (src[6] << 1) | BIT(0);
687                                         *dst++ = src[7];
688                                 }
689
690                                 src += 8;
691                                 added++;
692                         }
693                 }
694
695                 tr.len = chunk + added;
696
697                 tinydrm_dbg_spi_message(spi, &m);
698                 ret = spi_sync(spi, &m);
699                 if (ret)
700                         return ret;
701         }
702
703         return 0;
704 }
705
706 static int mipi_dbi_spi1_transfer(struct mipi_dbi *mipi, int dc,
707                                   const void *buf, size_t len,
708                                   unsigned int bpw)
709 {
710         struct spi_device *spi = mipi->spi;
711         struct spi_transfer tr = {
712                 .bits_per_word = 9,
713         };
714         const u16 *src16 = buf;
715         const u8 *src8 = buf;
716         struct spi_message m;
717         size_t max_chunk;
718         u16 *dst16;
719         int ret;
720
721         if (!tinydrm_spi_bpw_supported(spi, 9))
722                 return mipi_dbi_spi1e_transfer(mipi, dc, buf, len, bpw);
723
724         tr.speed_hz = mipi_dbi_spi_cmd_max_speed(spi, len);
725         max_chunk = mipi->tx_buf9_len;
726         dst16 = mipi->tx_buf9;
727
728         if (drm_debug & DRM_UT_DRIVER)
729                 pr_debug("[drm:%s] dc=%d, max_chunk=%zu, transfers:\n",
730                          __func__, dc, max_chunk);
731
732         max_chunk = min(max_chunk / 2, len);
733
734         spi_message_init_with_transfers(&m, &tr, 1);
735         tr.tx_buf = dst16;
736
737         while (len) {
738                 size_t chunk = min(len, max_chunk);
739                 unsigned int i;
740
741                 if (bpw == 16 && tinydrm_machine_little_endian()) {
742                         for (i = 0; i < (chunk * 2); i += 2) {
743                                 dst16[i]     = *src16 >> 8;
744                                 dst16[i + 1] = *src16++ & 0xFF;
745                                 if (dc) {
746                                         dst16[i]     |= 0x0100;
747                                         dst16[i + 1] |= 0x0100;
748                                 }
749                         }
750                 } else {
751                         for (i = 0; i < chunk; i++) {
752                                 dst16[i] = *src8++;
753                                 if (dc)
754                                         dst16[i] |= 0x0100;
755                         }
756                 }
757
758                 tr.len = chunk;
759                 len -= chunk;
760
761                 tinydrm_dbg_spi_message(spi, &m);
762                 ret = spi_sync(spi, &m);
763                 if (ret)
764                         return ret;
765         }
766
767         return 0;
768 }
769
770 static int mipi_dbi_typec1_command(struct mipi_dbi *mipi, u8 *cmd,
771                                    u8 *parameters, size_t num)
772 {
773         unsigned int bpw = (*cmd == MIPI_DCS_WRITE_MEMORY_START) ? 16 : 8;
774         int ret;
775
776         if (mipi_dbi_command_is_read(mipi, *cmd))
777                 return -ENOTSUPP;
778
779         MIPI_DBI_DEBUG_COMMAND(*cmd, parameters, num);
780
781         ret = mipi_dbi_spi1_transfer(mipi, 0, cmd, 1, 8);
782         if (ret || !num)
783                 return ret;
784
785         return mipi_dbi_spi1_transfer(mipi, 1, parameters, num, bpw);
786 }
787
788 /* MIPI DBI Type C Option 3 */
789
790 static int mipi_dbi_typec3_command_read(struct mipi_dbi *mipi, u8 *cmd,
791                                         u8 *data, size_t len)
792 {
793         struct spi_device *spi = mipi->spi;
794         u32 speed_hz = min_t(u32, MIPI_DBI_MAX_SPI_READ_SPEED,
795                              spi->max_speed_hz / 2);
796         struct spi_transfer tr[2] = {
797                 {
798                         .speed_hz = speed_hz,
799                         .tx_buf = cmd,
800                         .len = 1,
801                 }, {
802                         .speed_hz = speed_hz,
803                         .len = len,
804                 },
805         };
806         struct spi_message m;
807         u8 *buf;
808         int ret;
809
810         if (!len)
811                 return -EINVAL;
812
813         /*
814          * Support non-standard 24-bit and 32-bit Nokia read commands which
815          * start with a dummy clock, so we need to read an extra byte.
816          */
817         if (*cmd == MIPI_DCS_GET_DISPLAY_ID ||
818             *cmd == MIPI_DCS_GET_DISPLAY_STATUS) {
819                 if (!(len == 3 || len == 4))
820                         return -EINVAL;
821
822                 tr[1].len = len + 1;
823         }
824
825         buf = kmalloc(tr[1].len, GFP_KERNEL);
826         if (!buf)
827                 return -ENOMEM;
828
829         tr[1].rx_buf = buf;
830         gpiod_set_value_cansleep(mipi->dc, 0);
831
832         spi_message_init_with_transfers(&m, tr, ARRAY_SIZE(tr));
833         ret = spi_sync(spi, &m);
834         if (ret)
835                 goto err_free;
836
837         tinydrm_dbg_spi_message(spi, &m);
838
839         if (tr[1].len == len) {
840                 memcpy(data, buf, len);
841         } else {
842                 unsigned int i;
843
844                 for (i = 0; i < len; i++)
845                         data[i] = (buf[i] << 1) | !!(buf[i + 1] & BIT(7));
846         }
847
848         MIPI_DBI_DEBUG_COMMAND(*cmd, data, len);
849
850 err_free:
851         kfree(buf);
852
853         return ret;
854 }
855
856 static int mipi_dbi_typec3_command(struct mipi_dbi *mipi, u8 *cmd,
857                                    u8 *par, size_t num)
858 {
859         struct spi_device *spi = mipi->spi;
860         unsigned int bpw = 8;
861         u32 speed_hz;
862         int ret;
863
864         if (mipi_dbi_command_is_read(mipi, *cmd))
865                 return mipi_dbi_typec3_command_read(mipi, cmd, par, num);
866
867         MIPI_DBI_DEBUG_COMMAND(*cmd, par, num);
868
869         gpiod_set_value_cansleep(mipi->dc, 0);
870         speed_hz = mipi_dbi_spi_cmd_max_speed(spi, 1);
871         ret = tinydrm_spi_transfer(spi, speed_hz, NULL, 8, cmd, 1);
872         if (ret || !num)
873                 return ret;
874
875         if (*cmd == MIPI_DCS_WRITE_MEMORY_START && !mipi->swap_bytes)
876                 bpw = 16;
877
878         gpiod_set_value_cansleep(mipi->dc, 1);
879         speed_hz = mipi_dbi_spi_cmd_max_speed(spi, num);
880
881         return tinydrm_spi_transfer(spi, speed_hz, NULL, bpw, par, num);
882 }
883
884 /**
885  * mipi_dbi_spi_init - Initialize MIPI DBI SPI interfaced controller
886  * @spi: SPI device
887  * @mipi: &mipi_dbi structure to initialize
888  * @dc: D/C gpio (optional)
889  *
890  * This function sets &mipi_dbi->command, enables &mipi->read_commands for the
891  * usual read commands. It should be followed by a call to mipi_dbi_init() or
892  * a driver-specific init.
893  *
894  * If @dc is set, a Type C Option 3 interface is assumed, if not
895  * Type C Option 1.
896  *
897  * If the SPI master driver doesn't support the necessary bits per word,
898  * the following transformation is used:
899  *
900  * - 9-bit: reorder buffer as 9x 8-bit words, padded with no-op command.
901  * - 16-bit: if big endian send as 8-bit, if little endian swap bytes
902  *
903  * Returns:
904  * Zero on success, negative error code on failure.
905  */
906 int mipi_dbi_spi_init(struct spi_device *spi, struct mipi_dbi *mipi,
907                       struct gpio_desc *dc)
908 {
909         size_t tx_size = tinydrm_spi_max_transfer_size(spi, 0);
910         struct device *dev = &spi->dev;
911         int ret;
912
913         if (tx_size < 16) {
914                 DRM_ERROR("SPI transmit buffer too small: %zu\n", tx_size);
915                 return -EINVAL;
916         }
917
918         /*
919          * Even though it's not the SPI device that does DMA (the master does),
920          * the dma mask is necessary for the dma_alloc_wc() in
921          * drm_gem_cma_create(). The dma_addr returned will be a physical
922          * adddress which might be different from the bus address, but this is
923          * not a problem since the address will not be used.
924          * The virtual address is used in the transfer and the SPI core
925          * re-maps it on the SPI master device using the DMA streaming API
926          * (spi_map_buf()).
927          */
928         if (!dev->coherent_dma_mask) {
929                 ret = dma_coerce_mask_and_coherent(dev, DMA_BIT_MASK(32));
930                 if (ret) {
931                         dev_warn(dev, "Failed to set dma mask %d\n", ret);
932                         return ret;
933                 }
934         }
935
936         mipi->spi = spi;
937         mipi->read_commands = mipi_dbi_dcs_read_commands;
938
939         if (dc) {
940                 mipi->command = mipi_dbi_typec3_command;
941                 mipi->dc = dc;
942                 if (tinydrm_machine_little_endian() &&
943                     !tinydrm_spi_bpw_supported(spi, 16))
944                         mipi->swap_bytes = true;
945         } else {
946                 mipi->command = mipi_dbi_typec1_command;
947                 mipi->tx_buf9_len = tx_size;
948                 mipi->tx_buf9 = devm_kmalloc(dev, tx_size, GFP_KERNEL);
949                 if (!mipi->tx_buf9)
950                         return -ENOMEM;
951         }
952
953         DRM_DEBUG_DRIVER("SPI speed: %uMHz\n", spi->max_speed_hz / 1000000);
954
955         return 0;
956 }
957 EXPORT_SYMBOL(mipi_dbi_spi_init);
958
959 #endif /* CONFIG_SPI */
960
961 #ifdef CONFIG_DEBUG_FS
962
963 static ssize_t mipi_dbi_debugfs_command_write(struct file *file,
964                                               const char __user *ubuf,
965                                               size_t count, loff_t *ppos)
966 {
967         struct seq_file *m = file->private_data;
968         struct mipi_dbi *mipi = m->private;
969         u8 val, cmd = 0, parameters[64];
970         char *buf, *pos, *token;
971         unsigned int i;
972         int ret;
973
974         buf = memdup_user_nul(ubuf, count);
975         if (IS_ERR(buf))
976                 return PTR_ERR(buf);
977
978         /* strip trailing whitespace */
979         for (i = count - 1; i > 0; i--)
980                 if (isspace(buf[i]))
981                         buf[i] = '\0';
982                 else
983                         break;
984         i = 0;
985         pos = buf;
986         while (pos) {
987                 token = strsep(&pos, " ");
988                 if (!token) {
989                         ret = -EINVAL;
990                         goto err_free;
991                 }
992
993                 ret = kstrtou8(token, 16, &val);
994                 if (ret < 0)
995                         goto err_free;
996
997                 if (token == buf)
998                         cmd = val;
999                 else
1000                         parameters[i++] = val;
1001
1002                 if (i == 64) {
1003                         ret = -E2BIG;
1004                         goto err_free;
1005                 }
1006         }
1007
1008         ret = mipi_dbi_command_buf(mipi, cmd, parameters, i);
1009
1010 err_free:
1011         kfree(buf);
1012
1013         return ret < 0 ? ret : count;
1014 }
1015
1016 static int mipi_dbi_debugfs_command_show(struct seq_file *m, void *unused)
1017 {
1018         struct mipi_dbi *mipi = m->private;
1019         u8 cmd, val[4];
1020         size_t len;
1021         int ret;
1022
1023         for (cmd = 0; cmd < 255; cmd++) {
1024                 if (!mipi_dbi_command_is_read(mipi, cmd))
1025                         continue;
1026
1027                 switch (cmd) {
1028                 case MIPI_DCS_READ_MEMORY_START:
1029                 case MIPI_DCS_READ_MEMORY_CONTINUE:
1030                         len = 2;
1031                         break;
1032                 case MIPI_DCS_GET_DISPLAY_ID:
1033                         len = 3;
1034                         break;
1035                 case MIPI_DCS_GET_DISPLAY_STATUS:
1036                         len = 4;
1037                         break;
1038                 default:
1039                         len = 1;
1040                         break;
1041                 }
1042
1043                 seq_printf(m, "%02x: ", cmd);
1044                 ret = mipi_dbi_command_buf(mipi, cmd, val, len);
1045                 if (ret) {
1046                         seq_puts(m, "XX\n");
1047                         continue;
1048                 }
1049                 seq_printf(m, "%*phN\n", (int)len, val);
1050         }
1051
1052         return 0;
1053 }
1054
1055 static int mipi_dbi_debugfs_command_open(struct inode *inode,
1056                                          struct file *file)
1057 {
1058         return single_open(file, mipi_dbi_debugfs_command_show,
1059                            inode->i_private);
1060 }
1061
1062 static const struct file_operations mipi_dbi_debugfs_command_fops = {
1063         .owner = THIS_MODULE,
1064         .open = mipi_dbi_debugfs_command_open,
1065         .read = seq_read,
1066         .llseek = seq_lseek,
1067         .release = single_release,
1068         .write = mipi_dbi_debugfs_command_write,
1069 };
1070
1071 /**
1072  * mipi_dbi_debugfs_init - Create debugfs entries
1073  * @minor: DRM minor
1074  *
1075  * This function creates a 'command' debugfs file for sending commands to the
1076  * controller or getting the read command values.
1077  * Drivers can use this as their &drm_driver->debugfs_init callback.
1078  *
1079  * Returns:
1080  * Zero on success, negative error code on failure.
1081  */
1082 int mipi_dbi_debugfs_init(struct drm_minor *minor)
1083 {
1084         struct tinydrm_device *tdev = minor->dev->dev_private;
1085         struct mipi_dbi *mipi = mipi_dbi_from_tinydrm(tdev);
1086         umode_t mode = S_IFREG | S_IWUSR;
1087
1088         if (mipi->read_commands)
1089                 mode |= S_IRUGO;
1090         debugfs_create_file("command", mode, minor->debugfs_root, mipi,
1091                             &mipi_dbi_debugfs_command_fops);
1092
1093         return 0;
1094 }
1095 EXPORT_SYMBOL(mipi_dbi_debugfs_init);
1096
1097 #endif
1098
1099 MODULE_LICENSE("GPL");