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