1 /*
2  * Copyright (C) 2012-2016 Mentor Graphics Inc.
3  *
4  * Queued image conversion support, with tiling and rotation.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * for more details.
15  */
16 
17 #include <linux/interrupt.h>
18 #include <linux/dma-mapping.h>
19 #include <video/imx-ipu-image-convert.h>
20 #include "ipu-prv.h"
21 
22 /*
23  * The IC Resizer has a restriction that the output frame from the
24  * resizer must be 1024 or less in both width (pixels) and height
25  * (lines).
26  *
27  * The image converter attempts to split up a conversion when
28  * the desired output (converted) frame resolution exceeds the
29  * IC resizer limit of 1024 in either dimension.
30  *
31  * If either dimension of the output frame exceeds the limit, the
32  * dimension is split into 1, 2, or 4 equal stripes, for a maximum
33  * of 4*4 or 16 tiles. A conversion is then carried out for each
34  * tile (but taking care to pass the full frame stride length to
35  * the DMA channel's parameter memory!). IDMA double-buffering is used
36  * to convert each tile back-to-back when possible (see note below
37  * when double_buffering boolean is set).
38  *
39  * Note that the input frame must be split up into the same number
40  * of tiles as the output frame.
41  *
42  * FIXME: at this point there is no attempt to deal with visible seams
43  * at the tile boundaries when upscaling. The seams are caused by a reset
44  * of the bilinear upscale interpolation when starting a new tile. The
45  * seams are barely visible for small upscale factors, but become
46  * increasingly visible as the upscale factor gets larger, since more
47  * interpolated pixels get thrown out at the tile boundaries. A possilble
48  * fix might be to overlap tiles of different sizes, but this must be done
49  * while also maintaining the IDMAC dma buffer address alignment and 8x8 IRT
50  * alignment restrictions of each tile.
51  */
52 
53 #define MAX_STRIPES_W    4
54 #define MAX_STRIPES_H    4
55 #define MAX_TILES (MAX_STRIPES_W * MAX_STRIPES_H)
56 
57 #define MIN_W     16
58 #define MIN_H     8
59 #define MAX_W     4096
60 #define MAX_H     4096
61 
62 enum ipu_image_convert_type {
63 	IMAGE_CONVERT_IN = 0,
64 	IMAGE_CONVERT_OUT,
65 };
66 
67 struct ipu_image_convert_dma_buf {
68 	void          *virt;
69 	dma_addr_t    phys;
70 	unsigned long len;
71 };
72 
73 struct ipu_image_convert_dma_chan {
74 	int in;
75 	int out;
76 	int rot_in;
77 	int rot_out;
78 	int vdi_in_p;
79 	int vdi_in;
80 	int vdi_in_n;
81 };
82 
83 /* dimensions of one tile */
84 struct ipu_image_tile {
85 	u32 width;
86 	u32 height;
87 	u32 left;
88 	u32 top;
89 	/* size and strides are in bytes */
90 	u32 size;
91 	u32 stride;
92 	u32 rot_stride;
93 	/* start Y or packed offset of this tile */
94 	u32 offset;
95 	/* offset from start to tile in U plane, for planar formats */
96 	u32 u_off;
97 	/* offset from start to tile in V plane, for planar formats */
98 	u32 v_off;
99 };
100 
101 struct ipu_image_convert_image {
102 	struct ipu_image base;
103 	enum ipu_image_convert_type type;
104 
105 	const struct ipu_image_pixfmt *fmt;
106 	unsigned int stride;
107 
108 	/* # of rows (horizontal stripes) if dest height is > 1024 */
109 	unsigned int num_rows;
110 	/* # of columns (vertical stripes) if dest width is > 1024 */
111 	unsigned int num_cols;
112 
113 	struct ipu_image_tile tile[MAX_TILES];
114 };
115 
116 struct ipu_image_pixfmt {
117 	u32	fourcc;        /* V4L2 fourcc */
118 	int     bpp;           /* total bpp */
119 	int     uv_width_dec;  /* decimation in width for U/V planes */
120 	int     uv_height_dec; /* decimation in height for U/V planes */
121 	bool    planar;        /* planar format */
122 	bool    uv_swapped;    /* U and V planes are swapped */
123 	bool    uv_packed;     /* partial planar (U and V in same plane) */
124 };
125 
126 struct ipu_image_convert_ctx;
127 struct ipu_image_convert_chan;
128 struct ipu_image_convert_priv;
129 
130 struct ipu_image_convert_ctx {
131 	struct ipu_image_convert_chan *chan;
132 
133 	ipu_image_convert_cb_t complete;
134 	void *complete_context;
135 
136 	/* Source/destination image data and rotation mode */
137 	struct ipu_image_convert_image in;
138 	struct ipu_image_convert_image out;
139 	enum ipu_rotate_mode rot_mode;
140 	u32 downsize_coeff_h;
141 	u32 downsize_coeff_v;
142 	u32 image_resize_coeff_h;
143 	u32 image_resize_coeff_v;
144 	u32 resize_coeffs_h[MAX_STRIPES_W];
145 	u32 resize_coeffs_v[MAX_STRIPES_H];
146 
147 	/* intermediate buffer for rotation */
148 	struct ipu_image_convert_dma_buf rot_intermediate[2];
149 
150 	/* current buffer number for double buffering */
151 	int cur_buf_num;
152 
153 	bool aborting;
154 	struct completion aborted;
155 
156 	/* can we use double-buffering for this conversion operation? */
157 	bool double_buffering;
158 	/* num_rows * num_cols */
159 	unsigned int num_tiles;
160 	/* next tile to process */
161 	unsigned int next_tile;
162 	/* where to place converted tile in dest image */
163 	unsigned int out_tile_map[MAX_TILES];
164 
165 	struct list_head list;
166 };
167 
168 struct ipu_image_convert_chan {
169 	struct ipu_image_convert_priv *priv;
170 
171 	enum ipu_ic_task ic_task;
172 	const struct ipu_image_convert_dma_chan *dma_ch;
173 
174 	struct ipu_ic *ic;
175 	struct ipuv3_channel *in_chan;
176 	struct ipuv3_channel *out_chan;
177 	struct ipuv3_channel *rotation_in_chan;
178 	struct ipuv3_channel *rotation_out_chan;
179 
180 	/* the IPU end-of-frame irqs */
181 	int out_eof_irq;
182 	int rot_out_eof_irq;
183 
184 	spinlock_t irqlock;
185 
186 	/* list of convert contexts */
187 	struct list_head ctx_list;
188 	/* queue of conversion runs */
189 	struct list_head pending_q;
190 	/* queue of completed runs */
191 	struct list_head done_q;
192 
193 	/* the current conversion run */
194 	struct ipu_image_convert_run *current_run;
195 };
196 
197 struct ipu_image_convert_priv {
198 	struct ipu_image_convert_chan chan[IC_NUM_TASKS];
199 	struct ipu_soc *ipu;
200 };
201 
202 static const struct ipu_image_convert_dma_chan
203 image_convert_dma_chan[IC_NUM_TASKS] = {
204 	[IC_TASK_VIEWFINDER] = {
205 		.in = IPUV3_CHANNEL_MEM_IC_PRP_VF,
206 		.out = IPUV3_CHANNEL_IC_PRP_VF_MEM,
207 		.rot_in = IPUV3_CHANNEL_MEM_ROT_VF,
208 		.rot_out = IPUV3_CHANNEL_ROT_VF_MEM,
209 		.vdi_in_p = IPUV3_CHANNEL_MEM_VDI_PREV,
210 		.vdi_in = IPUV3_CHANNEL_MEM_VDI_CUR,
211 		.vdi_in_n = IPUV3_CHANNEL_MEM_VDI_NEXT,
212 	},
213 	[IC_TASK_POST_PROCESSOR] = {
214 		.in = IPUV3_CHANNEL_MEM_IC_PP,
215 		.out = IPUV3_CHANNEL_IC_PP_MEM,
216 		.rot_in = IPUV3_CHANNEL_MEM_ROT_PP,
217 		.rot_out = IPUV3_CHANNEL_ROT_PP_MEM,
218 	},
219 };
220 
221 static const struct ipu_image_pixfmt image_convert_formats[] = {
222 	{
223 		.fourcc	= V4L2_PIX_FMT_RGB565,
224 		.bpp    = 16,
225 	}, {
226 		.fourcc	= V4L2_PIX_FMT_RGB24,
227 		.bpp    = 24,
228 	}, {
229 		.fourcc	= V4L2_PIX_FMT_BGR24,
230 		.bpp    = 24,
231 	}, {
232 		.fourcc	= V4L2_PIX_FMT_RGB32,
233 		.bpp    = 32,
234 	}, {
235 		.fourcc	= V4L2_PIX_FMT_BGR32,
236 		.bpp    = 32,
237 	}, {
238 		.fourcc	= V4L2_PIX_FMT_XRGB32,
239 		.bpp    = 32,
240 	}, {
241 		.fourcc	= V4L2_PIX_FMT_XBGR32,
242 		.bpp    = 32,
243 	}, {
244 		.fourcc	= V4L2_PIX_FMT_YUYV,
245 		.bpp    = 16,
246 		.uv_width_dec = 2,
247 		.uv_height_dec = 1,
248 	}, {
249 		.fourcc	= V4L2_PIX_FMT_UYVY,
250 		.bpp    = 16,
251 		.uv_width_dec = 2,
252 		.uv_height_dec = 1,
253 	}, {
254 		.fourcc	= V4L2_PIX_FMT_YUV420,
255 		.bpp    = 12,
256 		.planar = true,
257 		.uv_width_dec = 2,
258 		.uv_height_dec = 2,
259 	}, {
260 		.fourcc	= V4L2_PIX_FMT_YVU420,
261 		.bpp    = 12,
262 		.planar = true,
263 		.uv_width_dec = 2,
264 		.uv_height_dec = 2,
265 		.uv_swapped = true,
266 	}, {
267 		.fourcc = V4L2_PIX_FMT_NV12,
268 		.bpp    = 12,
269 		.planar = true,
270 		.uv_width_dec = 2,
271 		.uv_height_dec = 2,
272 		.uv_packed = true,
273 	}, {
274 		.fourcc = V4L2_PIX_FMT_YUV422P,
275 		.bpp    = 16,
276 		.planar = true,
277 		.uv_width_dec = 2,
278 		.uv_height_dec = 1,
279 	}, {
280 		.fourcc = V4L2_PIX_FMT_NV16,
281 		.bpp    = 16,
282 		.planar = true,
283 		.uv_width_dec = 2,
284 		.uv_height_dec = 1,
285 		.uv_packed = true,
286 	},
287 };
288 
289 static const struct ipu_image_pixfmt *get_format(u32 fourcc)
290 {
291 	const struct ipu_image_pixfmt *ret = NULL;
292 	unsigned int i;
293 
294 	for (i = 0; i < ARRAY_SIZE(image_convert_formats); i++) {
295 		if (image_convert_formats[i].fourcc == fourcc) {
296 			ret = &image_convert_formats[i];
297 			break;
298 		}
299 	}
300 
301 	return ret;
302 }
303 
304 static void dump_format(struct ipu_image_convert_ctx *ctx,
305 			struct ipu_image_convert_image *ic_image)
306 {
307 	struct ipu_image_convert_chan *chan = ctx->chan;
308 	struct ipu_image_convert_priv *priv = chan->priv;
309 
310 	dev_dbg(priv->ipu->dev,
311 		"task %u: ctx %p: %s format: %dx%d (%dx%d tiles of size %dx%d), %c%c%c%c\n",
312 		chan->ic_task, ctx,
313 		ic_image->type == IMAGE_CONVERT_OUT ? "Output" : "Input",
314 		ic_image->base.pix.width, ic_image->base.pix.height,
315 		ic_image->num_cols, ic_image->num_rows,
316 		ic_image->tile[0].width, ic_image->tile[0].height,
317 		ic_image->fmt->fourcc & 0xff,
318 		(ic_image->fmt->fourcc >> 8) & 0xff,
319 		(ic_image->fmt->fourcc >> 16) & 0xff,
320 		(ic_image->fmt->fourcc >> 24) & 0xff);
321 }
322 
323 int ipu_image_convert_enum_format(int index, u32 *fourcc)
324 {
325 	const struct ipu_image_pixfmt *fmt;
326 
327 	if (index >= (int)ARRAY_SIZE(image_convert_formats))
328 		return -EINVAL;
329 
330 	/* Format found */
331 	fmt = &image_convert_formats[index];
332 	*fourcc = fmt->fourcc;
333 	return 0;
334 }
335 EXPORT_SYMBOL_GPL(ipu_image_convert_enum_format);
336 
337 static void free_dma_buf(struct ipu_image_convert_priv *priv,
338 			 struct ipu_image_convert_dma_buf *buf)
339 {
340 	if (buf->virt)
341 		dma_free_coherent(priv->ipu->dev,
342 				  buf->len, buf->virt, buf->phys);
343 	buf->virt = NULL;
344 	buf->phys = 0;
345 }
346 
347 static int alloc_dma_buf(struct ipu_image_convert_priv *priv,
348 			 struct ipu_image_convert_dma_buf *buf,
349 			 int size)
350 {
351 	buf->len = PAGE_ALIGN(size);
352 	buf->virt = dma_alloc_coherent(priv->ipu->dev, buf->len, &buf->phys,
353 				       GFP_DMA | GFP_KERNEL);
354 	if (!buf->virt) {
355 		dev_err(priv->ipu->dev, "failed to alloc dma buffer\n");
356 		return -ENOMEM;
357 	}
358 
359 	return 0;
360 }
361 
362 static inline int num_stripes(int dim)
363 {
364 	if (dim <= 1024)
365 		return 1;
366 	else if (dim <= 2048)
367 		return 2;
368 	else
369 		return 4;
370 }
371 
372 /*
373  * Calculate downsizing coefficients, which are the same for all tiles,
374  * and bilinear resizing coefficients, which are used to find the best
375  * seam positions.
376  */
377 static int calc_image_resize_coefficients(struct ipu_image_convert_ctx *ctx,
378 					  struct ipu_image *in,
379 					  struct ipu_image *out)
380 {
381 	u32 downsized_width = in->rect.width;
382 	u32 downsized_height = in->rect.height;
383 	u32 downsize_coeff_v = 0;
384 	u32 downsize_coeff_h = 0;
385 	u32 resized_width = out->rect.width;
386 	u32 resized_height = out->rect.height;
387 	u32 resize_coeff_h;
388 	u32 resize_coeff_v;
389 
390 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
391 		resized_width = out->rect.height;
392 		resized_height = out->rect.width;
393 	}
394 
395 	/* Do not let invalid input lead to an endless loop below */
396 	if (WARN_ON(resized_width == 0 || resized_height == 0))
397 		return -EINVAL;
398 
399 	while (downsized_width >= resized_width * 2) {
400 		downsized_width >>= 1;
401 		downsize_coeff_h++;
402 	}
403 
404 	while (downsized_height >= resized_height * 2) {
405 		downsized_height >>= 1;
406 		downsize_coeff_v++;
407 	}
408 
409 	/*
410 	 * Calculate the bilinear resizing coefficients that could be used if
411 	 * we were converting with a single tile. The bottom right output pixel
412 	 * should sample as close as possible to the bottom right input pixel
413 	 * out of the decimator, but not overshoot it:
414 	 */
415 	resize_coeff_h = 8192 * (downsized_width - 1) / (resized_width - 1);
416 	resize_coeff_v = 8192 * (downsized_height - 1) / (resized_height - 1);
417 
418 	dev_dbg(ctx->chan->priv->ipu->dev,
419 		"%s: hscale: >>%u, *8192/%u vscale: >>%u, *8192/%u, %ux%u tiles\n",
420 		__func__, downsize_coeff_h, resize_coeff_h, downsize_coeff_v,
421 		resize_coeff_v, ctx->in.num_cols, ctx->in.num_rows);
422 
423 	if (downsize_coeff_h > 2 || downsize_coeff_v  > 2 ||
424 	    resize_coeff_h > 0x3fff || resize_coeff_v > 0x3fff)
425 		return -EINVAL;
426 
427 	ctx->downsize_coeff_h = downsize_coeff_h;
428 	ctx->downsize_coeff_v = downsize_coeff_v;
429 	ctx->image_resize_coeff_h = resize_coeff_h;
430 	ctx->image_resize_coeff_v = resize_coeff_v;
431 
432 	return 0;
433 }
434 
435 #define round_closest(x, y) round_down((x) + (y)/2, (y))
436 
437 /*
438  * Find the best aligned seam position in the inverval [out_start, out_end].
439  * Rotation and image offsets are out of scope.
440  *
441  * @out_start: start of inverval, must be within 1024 pixels / lines
442  *             of out_end
443  * @out_end: end of interval, smaller than or equal to out_edge
444  * @in_edge: input right / bottom edge
445  * @out_edge: output right / bottom edge
446  * @in_align: input alignment, either horizontal 8-byte line start address
447  *            alignment, or pixel alignment due to image format
448  * @out_align: output alignment, either horizontal 8-byte line start address
449  *             alignment, or pixel alignment due to image format or rotator
450  *             block size
451  * @in_burst: horizontal input burst size in case of horizontal flip
452  * @out_burst: horizontal output burst size or rotator block size
453  * @downsize_coeff: downsizing section coefficient
454  * @resize_coeff: main processing section resizing coefficient
455  * @_in_seam: aligned input seam position return value
456  * @_out_seam: aligned output seam position return value
457  */
458 static void find_best_seam(struct ipu_image_convert_ctx *ctx,
459 			   unsigned int out_start,
460 			   unsigned int out_end,
461 			   unsigned int in_edge,
462 			   unsigned int out_edge,
463 			   unsigned int in_align,
464 			   unsigned int out_align,
465 			   unsigned int in_burst,
466 			   unsigned int out_burst,
467 			   unsigned int downsize_coeff,
468 			   unsigned int resize_coeff,
469 			   u32 *_in_seam,
470 			   u32 *_out_seam)
471 {
472 	struct device *dev = ctx->chan->priv->ipu->dev;
473 	unsigned int out_pos;
474 	/* Input / output seam position candidates */
475 	unsigned int out_seam = 0;
476 	unsigned int in_seam = 0;
477 	unsigned int min_diff = UINT_MAX;
478 
479 	/*
480 	 * Output tiles must start at a multiple of 8 bytes horizontally and
481 	 * possibly at an even line horizontally depending on the pixel format.
482 	 * Only consider output aligned positions for the seam.
483 	 */
484 	out_start = round_up(out_start, out_align);
485 	for (out_pos = out_start; out_pos < out_end; out_pos += out_align) {
486 		unsigned int in_pos;
487 		unsigned int in_pos_aligned;
488 		unsigned int abs_diff;
489 
490 		/*
491 		 * Tiles in the right row / bottom column may not be allowed to
492 		 * overshoot horizontally / vertically. out_burst may be the
493 		 * actual DMA burst size, or the rotator block size.
494 		 */
495 		if ((out_burst > 1) && (out_edge - out_pos) % out_burst)
496 			continue;
497 
498 		/*
499 		 * Input sample position, corresponding to out_pos, 19.13 fixed
500 		 * point.
501 		 */
502 		in_pos = (out_pos * resize_coeff) << downsize_coeff;
503 		/*
504 		 * The closest input sample position that we could actually
505 		 * start the input tile at, 19.13 fixed point.
506 		 */
507 		in_pos_aligned = round_closest(in_pos, 8192U * in_align);
508 
509 		if ((in_burst > 1) &&
510 		    (in_edge - in_pos_aligned / 8192U) % in_burst)
511 			continue;
512 
513 		if (in_pos < in_pos_aligned)
514 			abs_diff = in_pos_aligned - in_pos;
515 		else
516 			abs_diff = in_pos - in_pos_aligned;
517 
518 		if (abs_diff < min_diff) {
519 			in_seam = in_pos_aligned;
520 			out_seam = out_pos;
521 			min_diff = abs_diff;
522 		}
523 	}
524 
525 	*_out_seam = out_seam;
526 	/* Convert 19.13 fixed point to integer seam position */
527 	*_in_seam = DIV_ROUND_CLOSEST(in_seam, 8192U);
528 
529 	dev_dbg(dev, "%s: out_seam %u(%u) in [%u, %u], in_seam %u(%u) diff %u.%03u\n",
530 		__func__, out_seam, out_align, out_start, out_end,
531 		*_in_seam, in_align, min_diff / 8192,
532 		DIV_ROUND_CLOSEST(min_diff % 8192 * 1000, 8192));
533 }
534 
535 /*
536  * Tile left edges are required to be aligned to multiples of 8 bytes
537  * by the IDMAC.
538  */
539 static inline u32 tile_left_align(const struct ipu_image_pixfmt *fmt)
540 {
541 	if (fmt->planar)
542 		return fmt->uv_packed ? 8 : 8 * fmt->uv_width_dec;
543 	else
544 		return fmt->bpp == 32 ? 2 : fmt->bpp == 16 ? 4 : 8;
545 }
546 
547 /*
548  * Tile top edge alignment is only limited by chroma subsampling.
549  */
550 static inline u32 tile_top_align(const struct ipu_image_pixfmt *fmt)
551 {
552 	return fmt->uv_height_dec > 1 ? 2 : 1;
553 }
554 
555 /*
556  * We have to adjust the tile width such that the tile physaddrs and
557  * U and V plane offsets are multiples of 8 bytes as required by
558  * the IPU DMA Controller. For the planar formats, this corresponds
559  * to a pixel alignment of 16 (but use a more formal equation since
560  * the variables are available). For all the packed formats, 8 is
561  * good enough.
562  */
563 static inline u32 tile_width_align(const struct ipu_image_pixfmt *fmt)
564 {
565 	return fmt->planar ? 8 * fmt->uv_width_dec : 8;
566 }
567 
568 /*
569  * For tile height alignment, we have to ensure that the output tile
570  * heights are multiples of 8 lines if the IRT is required by the
571  * given rotation mode (the IRT performs rotations on 8x8 blocks
572  * at a time). If the IRT is not used, or for input image tiles,
573  * 2 lines are good enough.
574  */
575 static inline u32 tile_height_align(enum ipu_image_convert_type type,
576 				    enum ipu_rotate_mode rot_mode)
577 {
578 	return (type == IMAGE_CONVERT_OUT &&
579 		ipu_rot_mode_is_irt(rot_mode)) ? 8 : 2;
580 }
581 
582 /*
583  * Fill in left position and width and for all tiles in an input column, and
584  * for all corresponding output tiles. If the 90° rotator is used, the output
585  * tiles are in a row, and output tile top position and height are set.
586  */
587 static void fill_tile_column(struct ipu_image_convert_ctx *ctx,
588 			     unsigned int col,
589 			     struct ipu_image_convert_image *in,
590 			     unsigned int in_left, unsigned int in_width,
591 			     struct ipu_image_convert_image *out,
592 			     unsigned int out_left, unsigned int out_width)
593 {
594 	unsigned int row, tile_idx;
595 	struct ipu_image_tile *in_tile, *out_tile;
596 
597 	for (row = 0; row < in->num_rows; row++) {
598 		tile_idx = in->num_cols * row + col;
599 		in_tile = &in->tile[tile_idx];
600 		out_tile = &out->tile[ctx->out_tile_map[tile_idx]];
601 
602 		in_tile->left = in_left;
603 		in_tile->width = in_width;
604 
605 		if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
606 			out_tile->top = out_left;
607 			out_tile->height = out_width;
608 		} else {
609 			out_tile->left = out_left;
610 			out_tile->width = out_width;
611 		}
612 	}
613 }
614 
615 /*
616  * Fill in top position and height and for all tiles in an input row, and
617  * for all corresponding output tiles. If the 90° rotator is used, the output
618  * tiles are in a column, and output tile left position and width are set.
619  */
620 static void fill_tile_row(struct ipu_image_convert_ctx *ctx, unsigned int row,
621 			  struct ipu_image_convert_image *in,
622 			  unsigned int in_top, unsigned int in_height,
623 			  struct ipu_image_convert_image *out,
624 			  unsigned int out_top, unsigned int out_height)
625 {
626 	unsigned int col, tile_idx;
627 	struct ipu_image_tile *in_tile, *out_tile;
628 
629 	for (col = 0; col < in->num_cols; col++) {
630 		tile_idx = in->num_cols * row + col;
631 		in_tile = &in->tile[tile_idx];
632 		out_tile = &out->tile[ctx->out_tile_map[tile_idx]];
633 
634 		in_tile->top = in_top;
635 		in_tile->height = in_height;
636 
637 		if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
638 			out_tile->left = out_top;
639 			out_tile->width = out_height;
640 		} else {
641 			out_tile->top = out_top;
642 			out_tile->height = out_height;
643 		}
644 	}
645 }
646 
647 /*
648  * Find the best horizontal and vertical seam positions to split into tiles.
649  * Minimize the fractional part of the input sampling position for the
650  * top / left pixels of each tile.
651  */
652 static void find_seams(struct ipu_image_convert_ctx *ctx,
653 		       struct ipu_image_convert_image *in,
654 		       struct ipu_image_convert_image *out)
655 {
656 	struct device *dev = ctx->chan->priv->ipu->dev;
657 	unsigned int resized_width = out->base.rect.width;
658 	unsigned int resized_height = out->base.rect.height;
659 	unsigned int col;
660 	unsigned int row;
661 	unsigned int in_left_align = tile_left_align(in->fmt);
662 	unsigned int in_top_align = tile_top_align(in->fmt);
663 	unsigned int out_left_align = tile_left_align(out->fmt);
664 	unsigned int out_top_align = tile_top_align(out->fmt);
665 	unsigned int out_width_align = tile_width_align(out->fmt);
666 	unsigned int out_height_align = tile_height_align(out->type,
667 							  ctx->rot_mode);
668 	unsigned int in_right = in->base.rect.width;
669 	unsigned int in_bottom = in->base.rect.height;
670 	unsigned int out_right = out->base.rect.width;
671 	unsigned int out_bottom = out->base.rect.height;
672 	unsigned int flipped_out_left;
673 	unsigned int flipped_out_top;
674 
675 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
676 		/* Switch width/height and align top left to IRT block size */
677 		resized_width = out->base.rect.height;
678 		resized_height = out->base.rect.width;
679 		out_left_align = out_height_align;
680 		out_top_align = out_width_align;
681 		out_width_align = out_left_align;
682 		out_height_align = out_top_align;
683 		out_right = out->base.rect.height;
684 		out_bottom = out->base.rect.width;
685 	}
686 
687 	for (col = in->num_cols - 1; col > 0; col--) {
688 		bool allow_in_overshoot = ipu_rot_mode_is_irt(ctx->rot_mode) ||
689 					  !(ctx->rot_mode & IPU_ROT_BIT_HFLIP);
690 		bool allow_out_overshoot = (col < in->num_cols - 1) &&
691 					   !(ctx->rot_mode & IPU_ROT_BIT_HFLIP);
692 		unsigned int out_start;
693 		unsigned int out_end;
694 		unsigned int in_left;
695 		unsigned int out_left;
696 
697 		/*
698 		 * Align input width to burst length if the scaling step flips
699 		 * horizontally.
700 		 */
701 
702 		/* Start within 1024 pixels of the right edge */
703 		out_start = max_t(int, 0, out_right - 1024);
704 		/* End before having to add more columns to the left */
705 		out_end = min_t(unsigned int, out_right, col * 1024);
706 
707 		find_best_seam(ctx, out_start, out_end,
708 			       in_right, out_right,
709 			       in_left_align, out_left_align,
710 			       allow_in_overshoot ? 1 : 8 /* burst length */,
711 			       allow_out_overshoot ? 1 : out_width_align,
712 			       ctx->downsize_coeff_h, ctx->image_resize_coeff_h,
713 			       &in_left, &out_left);
714 
715 		if (ctx->rot_mode & IPU_ROT_BIT_HFLIP)
716 			flipped_out_left = resized_width - out_right;
717 		else
718 			flipped_out_left = out_left;
719 
720 		fill_tile_column(ctx, col, in, in_left, in_right - in_left,
721 				 out, flipped_out_left, out_right - out_left);
722 
723 		dev_dbg(dev, "%s: col %u: %u, %u -> %u, %u\n", __func__, col,
724 			in_left, in_right - in_left,
725 			flipped_out_left, out_right - out_left);
726 
727 		in_right = in_left;
728 		out_right = out_left;
729 	}
730 
731 	flipped_out_left = (ctx->rot_mode & IPU_ROT_BIT_HFLIP) ?
732 			   resized_width - out_right : 0;
733 
734 	fill_tile_column(ctx, 0, in, 0, in_right,
735 			 out, flipped_out_left, out_right);
736 
737 	dev_dbg(dev, "%s: col 0: 0, %u -> %u, %u\n", __func__,
738 		in_right, flipped_out_left, out_right);
739 
740 	for (row = in->num_rows - 1; row > 0; row--) {
741 		bool allow_overshoot = row < in->num_rows - 1;
742 		unsigned int out_start;
743 		unsigned int out_end;
744 		unsigned int in_top;
745 		unsigned int out_top;
746 
747 		/* Start within 1024 lines of the bottom edge */
748 		out_start = max_t(int, 0, out_bottom - 1024);
749 		/* End before having to add more rows above */
750 		out_end = min_t(unsigned int, out_bottom, row * 1024);
751 
752 		find_best_seam(ctx, out_start, out_end,
753 			       in_bottom, out_bottom,
754 			       in_top_align, out_top_align,
755 			       1, allow_overshoot ? 1 : out_height_align,
756 			       ctx->downsize_coeff_v, ctx->image_resize_coeff_v,
757 			       &in_top, &out_top);
758 
759 		if ((ctx->rot_mode & IPU_ROT_BIT_VFLIP) ^
760 		    ipu_rot_mode_is_irt(ctx->rot_mode))
761 			flipped_out_top = resized_height - out_bottom;
762 		else
763 			flipped_out_top = out_top;
764 
765 		fill_tile_row(ctx, row, in, in_top, in_bottom - in_top,
766 			      out, flipped_out_top, out_bottom - out_top);
767 
768 		dev_dbg(dev, "%s: row %u: %u, %u -> %u, %u\n", __func__, row,
769 			in_top, in_bottom - in_top,
770 			flipped_out_top, out_bottom - out_top);
771 
772 		in_bottom = in_top;
773 		out_bottom = out_top;
774 	}
775 
776 	if ((ctx->rot_mode & IPU_ROT_BIT_VFLIP) ^
777 	    ipu_rot_mode_is_irt(ctx->rot_mode))
778 		flipped_out_top = resized_height - out_bottom;
779 	else
780 		flipped_out_top = 0;
781 
782 	fill_tile_row(ctx, 0, in, 0, in_bottom,
783 		      out, flipped_out_top, out_bottom);
784 
785 	dev_dbg(dev, "%s: row 0: 0, %u -> %u, %u\n", __func__,
786 		in_bottom, flipped_out_top, out_bottom);
787 }
788 
789 static void calc_tile_dimensions(struct ipu_image_convert_ctx *ctx,
790 				 struct ipu_image_convert_image *image)
791 {
792 	unsigned int i;
793 
794 	for (i = 0; i < ctx->num_tiles; i++) {
795 		struct ipu_image_tile *tile;
796 		const unsigned int row = i / image->num_cols;
797 		const unsigned int col = i % image->num_cols;
798 
799 		if (image->type == IMAGE_CONVERT_OUT)
800 			tile = &image->tile[ctx->out_tile_map[i]];
801 		else
802 			tile = &image->tile[i];
803 
804 		tile->size = ((tile->height * image->fmt->bpp) >> 3) *
805 			tile->width;
806 
807 		if (image->fmt->planar) {
808 			tile->stride = tile->width;
809 			tile->rot_stride = tile->height;
810 		} else {
811 			tile->stride =
812 				(image->fmt->bpp * tile->width) >> 3;
813 			tile->rot_stride =
814 				(image->fmt->bpp * tile->height) >> 3;
815 		}
816 	}
817 }
818 
819 /*
820  * Use the rotation transformation to find the tile coordinates
821  * (row, col) of a tile in the destination frame that corresponds
822  * to the given tile coordinates of a source frame. The destination
823  * coordinate is then converted to a tile index.
824  */
825 static int transform_tile_index(struct ipu_image_convert_ctx *ctx,
826 				int src_row, int src_col)
827 {
828 	struct ipu_image_convert_chan *chan = ctx->chan;
829 	struct ipu_image_convert_priv *priv = chan->priv;
830 	struct ipu_image_convert_image *s_image = &ctx->in;
831 	struct ipu_image_convert_image *d_image = &ctx->out;
832 	int dst_row, dst_col;
833 
834 	/* with no rotation it's a 1:1 mapping */
835 	if (ctx->rot_mode == IPU_ROTATE_NONE)
836 		return src_row * s_image->num_cols + src_col;
837 
838 	/*
839 	 * before doing the transform, first we have to translate
840 	 * source row,col for an origin in the center of s_image
841 	 */
842 	src_row = src_row * 2 - (s_image->num_rows - 1);
843 	src_col = src_col * 2 - (s_image->num_cols - 1);
844 
845 	/* do the rotation transform */
846 	if (ctx->rot_mode & IPU_ROT_BIT_90) {
847 		dst_col = -src_row;
848 		dst_row = src_col;
849 	} else {
850 		dst_col = src_col;
851 		dst_row = src_row;
852 	}
853 
854 	/* apply flip */
855 	if (ctx->rot_mode & IPU_ROT_BIT_HFLIP)
856 		dst_col = -dst_col;
857 	if (ctx->rot_mode & IPU_ROT_BIT_VFLIP)
858 		dst_row = -dst_row;
859 
860 	dev_dbg(priv->ipu->dev, "task %u: ctx %p: [%d,%d] --> [%d,%d]\n",
861 		chan->ic_task, ctx, src_col, src_row, dst_col, dst_row);
862 
863 	/*
864 	 * finally translate dest row,col using an origin in upper
865 	 * left of d_image
866 	 */
867 	dst_row += d_image->num_rows - 1;
868 	dst_col += d_image->num_cols - 1;
869 	dst_row /= 2;
870 	dst_col /= 2;
871 
872 	return dst_row * d_image->num_cols + dst_col;
873 }
874 
875 /*
876  * Fill the out_tile_map[] with transformed destination tile indeces.
877  */
878 static void calc_out_tile_map(struct ipu_image_convert_ctx *ctx)
879 {
880 	struct ipu_image_convert_image *s_image = &ctx->in;
881 	unsigned int row, col, tile = 0;
882 
883 	for (row = 0; row < s_image->num_rows; row++) {
884 		for (col = 0; col < s_image->num_cols; col++) {
885 			ctx->out_tile_map[tile] =
886 				transform_tile_index(ctx, row, col);
887 			tile++;
888 		}
889 	}
890 }
891 
892 static int calc_tile_offsets_planar(struct ipu_image_convert_ctx *ctx,
893 				    struct ipu_image_convert_image *image)
894 {
895 	struct ipu_image_convert_chan *chan = ctx->chan;
896 	struct ipu_image_convert_priv *priv = chan->priv;
897 	const struct ipu_image_pixfmt *fmt = image->fmt;
898 	unsigned int row, col, tile = 0;
899 	u32 H, top, y_stride, uv_stride;
900 	u32 uv_row_off, uv_col_off, uv_off, u_off, v_off, tmp;
901 	u32 y_row_off, y_col_off, y_off;
902 	u32 y_size, uv_size;
903 
904 	/* setup some convenience vars */
905 	H = image->base.pix.height;
906 
907 	y_stride = image->stride;
908 	uv_stride = y_stride / fmt->uv_width_dec;
909 	if (fmt->uv_packed)
910 		uv_stride *= 2;
911 
912 	y_size = H * y_stride;
913 	uv_size = y_size / (fmt->uv_width_dec * fmt->uv_height_dec);
914 
915 	for (row = 0; row < image->num_rows; row++) {
916 		top = image->tile[tile].top;
917 		y_row_off = top * y_stride;
918 		uv_row_off = (top * uv_stride) / fmt->uv_height_dec;
919 
920 		for (col = 0; col < image->num_cols; col++) {
921 			y_col_off = image->tile[tile].left;
922 			uv_col_off = y_col_off / fmt->uv_width_dec;
923 			if (fmt->uv_packed)
924 				uv_col_off *= 2;
925 
926 			y_off = y_row_off + y_col_off;
927 			uv_off = uv_row_off + uv_col_off;
928 
929 			u_off = y_size - y_off + uv_off;
930 			v_off = (fmt->uv_packed) ? 0 : u_off + uv_size;
931 			if (fmt->uv_swapped) {
932 				tmp = u_off;
933 				u_off = v_off;
934 				v_off = tmp;
935 			}
936 
937 			image->tile[tile].offset = y_off;
938 			image->tile[tile].u_off = u_off;
939 			image->tile[tile++].v_off = v_off;
940 
941 			if ((y_off & 0x7) || (u_off & 0x7) || (v_off & 0x7)) {
942 				dev_err(priv->ipu->dev,
943 					"task %u: ctx %p: %s@[%d,%d]: "
944 					"y_off %08x, u_off %08x, v_off %08x\n",
945 					chan->ic_task, ctx,
946 					image->type == IMAGE_CONVERT_IN ?
947 					"Input" : "Output", row, col,
948 					y_off, u_off, v_off);
949 				return -EINVAL;
950 			}
951 		}
952 	}
953 
954 	return 0;
955 }
956 
957 static int calc_tile_offsets_packed(struct ipu_image_convert_ctx *ctx,
958 				    struct ipu_image_convert_image *image)
959 {
960 	struct ipu_image_convert_chan *chan = ctx->chan;
961 	struct ipu_image_convert_priv *priv = chan->priv;
962 	const struct ipu_image_pixfmt *fmt = image->fmt;
963 	unsigned int row, col, tile = 0;
964 	u32 bpp, stride, offset;
965 	u32 row_off, col_off;
966 
967 	/* setup some convenience vars */
968 	stride = image->stride;
969 	bpp = fmt->bpp;
970 
971 	for (row = 0; row < image->num_rows; row++) {
972 		row_off = image->tile[tile].top * stride;
973 
974 		for (col = 0; col < image->num_cols; col++) {
975 			col_off = (image->tile[tile].left * bpp) >> 3;
976 
977 			offset = row_off + col_off;
978 
979 			image->tile[tile].offset = offset;
980 			image->tile[tile].u_off = 0;
981 			image->tile[tile++].v_off = 0;
982 
983 			if (offset & 0x7) {
984 				dev_err(priv->ipu->dev,
985 					"task %u: ctx %p: %s@[%d,%d]: "
986 					"phys %08x\n",
987 					chan->ic_task, ctx,
988 					image->type == IMAGE_CONVERT_IN ?
989 					"Input" : "Output", row, col,
990 					row_off + col_off);
991 				return -EINVAL;
992 			}
993 		}
994 	}
995 
996 	return 0;
997 }
998 
999 static int calc_tile_offsets(struct ipu_image_convert_ctx *ctx,
1000 			      struct ipu_image_convert_image *image)
1001 {
1002 	if (image->fmt->planar)
1003 		return calc_tile_offsets_planar(ctx, image);
1004 
1005 	return calc_tile_offsets_packed(ctx, image);
1006 }
1007 
1008 /*
1009  * Calculate the resizing ratio for the IC main processing section given input
1010  * size, fixed downsizing coefficient, and output size.
1011  * Either round to closest for the next tile's first pixel to minimize seams
1012  * and distortion (for all but right column / bottom row), or round down to
1013  * avoid sampling beyond the edges of the input image for this tile's last
1014  * pixel.
1015  * Returns the resizing coefficient, resizing ratio is 8192.0 / resize_coeff.
1016  */
1017 static u32 calc_resize_coeff(u32 input_size, u32 downsize_coeff,
1018 			     u32 output_size, bool allow_overshoot)
1019 {
1020 	u32 downsized = input_size >> downsize_coeff;
1021 
1022 	if (allow_overshoot)
1023 		return DIV_ROUND_CLOSEST(8192 * downsized, output_size);
1024 	else
1025 		return 8192 * (downsized - 1) / (output_size - 1);
1026 }
1027 
1028 /*
1029  * Slightly modify resize coefficients per tile to hide the bilinear
1030  * interpolator reset at tile borders, shifting the right / bottom edge
1031  * by up to a half input pixel. This removes noticeable seams between
1032  * tiles at higher upscaling factors.
1033  */
1034 static void calc_tile_resize_coefficients(struct ipu_image_convert_ctx *ctx)
1035 {
1036 	struct ipu_image_convert_chan *chan = ctx->chan;
1037 	struct ipu_image_convert_priv *priv = chan->priv;
1038 	struct ipu_image_tile *in_tile, *out_tile;
1039 	unsigned int col, row, tile_idx;
1040 	unsigned int last_output;
1041 
1042 	for (col = 0; col < ctx->in.num_cols; col++) {
1043 		bool closest = (col < ctx->in.num_cols - 1) &&
1044 			       !(ctx->rot_mode & IPU_ROT_BIT_HFLIP);
1045 		u32 resized_width;
1046 		u32 resize_coeff_h;
1047 
1048 		tile_idx = col;
1049 		in_tile = &ctx->in.tile[tile_idx];
1050 		out_tile = &ctx->out.tile[ctx->out_tile_map[tile_idx]];
1051 
1052 		if (ipu_rot_mode_is_irt(ctx->rot_mode))
1053 			resized_width = out_tile->height;
1054 		else
1055 			resized_width = out_tile->width;
1056 
1057 		resize_coeff_h = calc_resize_coeff(in_tile->width,
1058 						   ctx->downsize_coeff_h,
1059 						   resized_width, closest);
1060 
1061 		dev_dbg(priv->ipu->dev, "%s: column %u hscale: *8192/%u\n",
1062 			__func__, col, resize_coeff_h);
1063 
1064 
1065 		for (row = 0; row < ctx->in.num_rows; row++) {
1066 			tile_idx = row * ctx->in.num_cols + col;
1067 			in_tile = &ctx->in.tile[tile_idx];
1068 			out_tile = &ctx->out.tile[ctx->out_tile_map[tile_idx]];
1069 
1070 			/*
1071 			 * With the horizontal scaling factor known, round up
1072 			 * resized width (output width or height) to burst size.
1073 			 */
1074 			if (ipu_rot_mode_is_irt(ctx->rot_mode))
1075 				out_tile->height = round_up(resized_width, 8);
1076 			else
1077 				out_tile->width = round_up(resized_width, 8);
1078 
1079 			/*
1080 			 * Calculate input width from the last accessed input
1081 			 * pixel given resized width and scaling coefficients.
1082 			 * Round up to burst size.
1083 			 */
1084 			last_output = round_up(resized_width, 8) - 1;
1085 			if (closest)
1086 				last_output++;
1087 			in_tile->width = round_up(
1088 				(DIV_ROUND_UP(last_output * resize_coeff_h,
1089 					      8192) + 1)
1090 				<< ctx->downsize_coeff_h, 8);
1091 		}
1092 
1093 		ctx->resize_coeffs_h[col] = resize_coeff_h;
1094 	}
1095 
1096 	for (row = 0; row < ctx->in.num_rows; row++) {
1097 		bool closest = (row < ctx->in.num_rows - 1) &&
1098 			       !(ctx->rot_mode & IPU_ROT_BIT_VFLIP);
1099 		u32 resized_height;
1100 		u32 resize_coeff_v;
1101 
1102 		tile_idx = row * ctx->in.num_cols;
1103 		in_tile = &ctx->in.tile[tile_idx];
1104 		out_tile = &ctx->out.tile[ctx->out_tile_map[tile_idx]];
1105 
1106 		if (ipu_rot_mode_is_irt(ctx->rot_mode))
1107 			resized_height = out_tile->width;
1108 		else
1109 			resized_height = out_tile->height;
1110 
1111 		resize_coeff_v = calc_resize_coeff(in_tile->height,
1112 						   ctx->downsize_coeff_v,
1113 						   resized_height, closest);
1114 
1115 		dev_dbg(priv->ipu->dev, "%s: row %u vscale: *8192/%u\n",
1116 			__func__, row, resize_coeff_v);
1117 
1118 		for (col = 0; col < ctx->in.num_cols; col++) {
1119 			tile_idx = row * ctx->in.num_cols + col;
1120 			in_tile = &ctx->in.tile[tile_idx];
1121 			out_tile = &ctx->out.tile[ctx->out_tile_map[tile_idx]];
1122 
1123 			/*
1124 			 * With the vertical scaling factor known, round up
1125 			 * resized height (output width or height) to IDMAC
1126 			 * limitations.
1127 			 */
1128 			if (ipu_rot_mode_is_irt(ctx->rot_mode))
1129 				out_tile->width = round_up(resized_height, 2);
1130 			else
1131 				out_tile->height = round_up(resized_height, 2);
1132 
1133 			/*
1134 			 * Calculate input width from the last accessed input
1135 			 * pixel given resized height and scaling coefficients.
1136 			 * Align to IDMAC restrictions.
1137 			 */
1138 			last_output = round_up(resized_height, 2) - 1;
1139 			if (closest)
1140 				last_output++;
1141 			in_tile->height = round_up(
1142 				(DIV_ROUND_UP(last_output * resize_coeff_v,
1143 					      8192) + 1)
1144 				<< ctx->downsize_coeff_v, 2);
1145 		}
1146 
1147 		ctx->resize_coeffs_v[row] = resize_coeff_v;
1148 	}
1149 }
1150 
1151 /*
1152  * return the number of runs in given queue (pending_q or done_q)
1153  * for this context. hold irqlock when calling.
1154  */
1155 static int get_run_count(struct ipu_image_convert_ctx *ctx,
1156 			 struct list_head *q)
1157 {
1158 	struct ipu_image_convert_run *run;
1159 	int count = 0;
1160 
1161 	lockdep_assert_held(&ctx->chan->irqlock);
1162 
1163 	list_for_each_entry(run, q, list) {
1164 		if (run->ctx == ctx)
1165 			count++;
1166 	}
1167 
1168 	return count;
1169 }
1170 
1171 static void convert_stop(struct ipu_image_convert_run *run)
1172 {
1173 	struct ipu_image_convert_ctx *ctx = run->ctx;
1174 	struct ipu_image_convert_chan *chan = ctx->chan;
1175 	struct ipu_image_convert_priv *priv = chan->priv;
1176 
1177 	dev_dbg(priv->ipu->dev, "%s: task %u: stopping ctx %p run %p\n",
1178 		__func__, chan->ic_task, ctx, run);
1179 
1180 	/* disable IC tasks and the channels */
1181 	ipu_ic_task_disable(chan->ic);
1182 	ipu_idmac_disable_channel(chan->in_chan);
1183 	ipu_idmac_disable_channel(chan->out_chan);
1184 
1185 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1186 		ipu_idmac_disable_channel(chan->rotation_in_chan);
1187 		ipu_idmac_disable_channel(chan->rotation_out_chan);
1188 		ipu_idmac_unlink(chan->out_chan, chan->rotation_in_chan);
1189 	}
1190 
1191 	ipu_ic_disable(chan->ic);
1192 }
1193 
1194 static void init_idmac_channel(struct ipu_image_convert_ctx *ctx,
1195 			       struct ipuv3_channel *channel,
1196 			       struct ipu_image_convert_image *image,
1197 			       enum ipu_rotate_mode rot_mode,
1198 			       bool rot_swap_width_height,
1199 			       unsigned int tile)
1200 {
1201 	struct ipu_image_convert_chan *chan = ctx->chan;
1202 	unsigned int burst_size;
1203 	u32 width, height, stride;
1204 	dma_addr_t addr0, addr1 = 0;
1205 	struct ipu_image tile_image;
1206 	unsigned int tile_idx[2];
1207 
1208 	if (image->type == IMAGE_CONVERT_OUT) {
1209 		tile_idx[0] = ctx->out_tile_map[tile];
1210 		tile_idx[1] = ctx->out_tile_map[1];
1211 	} else {
1212 		tile_idx[0] = tile;
1213 		tile_idx[1] = 1;
1214 	}
1215 
1216 	if (rot_swap_width_height) {
1217 		width = image->tile[tile_idx[0]].height;
1218 		height = image->tile[tile_idx[0]].width;
1219 		stride = image->tile[tile_idx[0]].rot_stride;
1220 		addr0 = ctx->rot_intermediate[0].phys;
1221 		if (ctx->double_buffering)
1222 			addr1 = ctx->rot_intermediate[1].phys;
1223 	} else {
1224 		width = image->tile[tile_idx[0]].width;
1225 		height = image->tile[tile_idx[0]].height;
1226 		stride = image->stride;
1227 		addr0 = image->base.phys0 +
1228 			image->tile[tile_idx[0]].offset;
1229 		if (ctx->double_buffering)
1230 			addr1 = image->base.phys0 +
1231 				image->tile[tile_idx[1]].offset;
1232 	}
1233 
1234 	ipu_cpmem_zero(channel);
1235 
1236 	memset(&tile_image, 0, sizeof(tile_image));
1237 	tile_image.pix.width = tile_image.rect.width = width;
1238 	tile_image.pix.height = tile_image.rect.height = height;
1239 	tile_image.pix.bytesperline = stride;
1240 	tile_image.pix.pixelformat =  image->fmt->fourcc;
1241 	tile_image.phys0 = addr0;
1242 	tile_image.phys1 = addr1;
1243 	if (image->fmt->planar && !rot_swap_width_height) {
1244 		tile_image.u_offset = image->tile[tile_idx[0]].u_off;
1245 		tile_image.v_offset = image->tile[tile_idx[0]].v_off;
1246 	}
1247 
1248 	ipu_cpmem_set_image(channel, &tile_image);
1249 
1250 	if (rot_mode)
1251 		ipu_cpmem_set_rotation(channel, rot_mode);
1252 
1253 	if (channel == chan->rotation_in_chan ||
1254 	    channel == chan->rotation_out_chan) {
1255 		burst_size = 8;
1256 		ipu_cpmem_set_block_mode(channel);
1257 	} else
1258 		burst_size = (width % 16) ? 8 : 16;
1259 
1260 	ipu_cpmem_set_burstsize(channel, burst_size);
1261 
1262 	ipu_ic_task_idma_init(chan->ic, channel, width, height,
1263 			      burst_size, rot_mode);
1264 
1265 	/*
1266 	 * Setting a non-zero AXI ID collides with the PRG AXI snooping, so
1267 	 * only do this when there is no PRG present.
1268 	 */
1269 	if (!channel->ipu->prg_priv)
1270 		ipu_cpmem_set_axi_id(channel, 1);
1271 
1272 	ipu_idmac_set_double_buffer(channel, ctx->double_buffering);
1273 }
1274 
1275 static int convert_start(struct ipu_image_convert_run *run, unsigned int tile)
1276 {
1277 	struct ipu_image_convert_ctx *ctx = run->ctx;
1278 	struct ipu_image_convert_chan *chan = ctx->chan;
1279 	struct ipu_image_convert_priv *priv = chan->priv;
1280 	struct ipu_image_convert_image *s_image = &ctx->in;
1281 	struct ipu_image_convert_image *d_image = &ctx->out;
1282 	enum ipu_color_space src_cs, dest_cs;
1283 	unsigned int dst_tile = ctx->out_tile_map[tile];
1284 	unsigned int dest_width, dest_height;
1285 	unsigned int col, row;
1286 	u32 rsc;
1287 	int ret;
1288 
1289 	dev_dbg(priv->ipu->dev, "%s: task %u: starting ctx %p run %p tile %u -> %u\n",
1290 		__func__, chan->ic_task, ctx, run, tile, dst_tile);
1291 
1292 	src_cs = ipu_pixelformat_to_colorspace(s_image->fmt->fourcc);
1293 	dest_cs = ipu_pixelformat_to_colorspace(d_image->fmt->fourcc);
1294 
1295 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1296 		/* swap width/height for resizer */
1297 		dest_width = d_image->tile[dst_tile].height;
1298 		dest_height = d_image->tile[dst_tile].width;
1299 	} else {
1300 		dest_width = d_image->tile[dst_tile].width;
1301 		dest_height = d_image->tile[dst_tile].height;
1302 	}
1303 
1304 	row = tile / s_image->num_cols;
1305 	col = tile % s_image->num_cols;
1306 
1307 	rsc =  (ctx->downsize_coeff_v << 30) |
1308 	       (ctx->resize_coeffs_v[row] << 16) |
1309 	       (ctx->downsize_coeff_h << 14) |
1310 	       (ctx->resize_coeffs_h[col]);
1311 
1312 	dev_dbg(priv->ipu->dev, "%s: %ux%u -> %ux%u (rsc = 0x%x)\n",
1313 		__func__, s_image->tile[tile].width,
1314 		s_image->tile[tile].height, dest_width, dest_height, rsc);
1315 
1316 	/* setup the IC resizer and CSC */
1317 	ret = ipu_ic_task_init_rsc(chan->ic,
1318 			       s_image->tile[tile].width,
1319 			       s_image->tile[tile].height,
1320 			       dest_width,
1321 			       dest_height,
1322 			       src_cs, dest_cs,
1323 			       rsc);
1324 	if (ret) {
1325 		dev_err(priv->ipu->dev, "ipu_ic_task_init failed, %d\n", ret);
1326 		return ret;
1327 	}
1328 
1329 	/* init the source MEM-->IC PP IDMAC channel */
1330 	init_idmac_channel(ctx, chan->in_chan, s_image,
1331 			   IPU_ROTATE_NONE, false, tile);
1332 
1333 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1334 		/* init the IC PP-->MEM IDMAC channel */
1335 		init_idmac_channel(ctx, chan->out_chan, d_image,
1336 				   IPU_ROTATE_NONE, true, tile);
1337 
1338 		/* init the MEM-->IC PP ROT IDMAC channel */
1339 		init_idmac_channel(ctx, chan->rotation_in_chan, d_image,
1340 				   ctx->rot_mode, true, tile);
1341 
1342 		/* init the destination IC PP ROT-->MEM IDMAC channel */
1343 		init_idmac_channel(ctx, chan->rotation_out_chan, d_image,
1344 				   IPU_ROTATE_NONE, false, tile);
1345 
1346 		/* now link IC PP-->MEM to MEM-->IC PP ROT */
1347 		ipu_idmac_link(chan->out_chan, chan->rotation_in_chan);
1348 	} else {
1349 		/* init the destination IC PP-->MEM IDMAC channel */
1350 		init_idmac_channel(ctx, chan->out_chan, d_image,
1351 				   ctx->rot_mode, false, tile);
1352 	}
1353 
1354 	/* enable the IC */
1355 	ipu_ic_enable(chan->ic);
1356 
1357 	/* set buffers ready */
1358 	ipu_idmac_select_buffer(chan->in_chan, 0);
1359 	ipu_idmac_select_buffer(chan->out_chan, 0);
1360 	if (ipu_rot_mode_is_irt(ctx->rot_mode))
1361 		ipu_idmac_select_buffer(chan->rotation_out_chan, 0);
1362 	if (ctx->double_buffering) {
1363 		ipu_idmac_select_buffer(chan->in_chan, 1);
1364 		ipu_idmac_select_buffer(chan->out_chan, 1);
1365 		if (ipu_rot_mode_is_irt(ctx->rot_mode))
1366 			ipu_idmac_select_buffer(chan->rotation_out_chan, 1);
1367 	}
1368 
1369 	/* enable the channels! */
1370 	ipu_idmac_enable_channel(chan->in_chan);
1371 	ipu_idmac_enable_channel(chan->out_chan);
1372 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1373 		ipu_idmac_enable_channel(chan->rotation_in_chan);
1374 		ipu_idmac_enable_channel(chan->rotation_out_chan);
1375 	}
1376 
1377 	ipu_ic_task_enable(chan->ic);
1378 
1379 	ipu_cpmem_dump(chan->in_chan);
1380 	ipu_cpmem_dump(chan->out_chan);
1381 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1382 		ipu_cpmem_dump(chan->rotation_in_chan);
1383 		ipu_cpmem_dump(chan->rotation_out_chan);
1384 	}
1385 
1386 	ipu_dump(priv->ipu);
1387 
1388 	return 0;
1389 }
1390 
1391 /* hold irqlock when calling */
1392 static int do_run(struct ipu_image_convert_run *run)
1393 {
1394 	struct ipu_image_convert_ctx *ctx = run->ctx;
1395 	struct ipu_image_convert_chan *chan = ctx->chan;
1396 
1397 	lockdep_assert_held(&chan->irqlock);
1398 
1399 	ctx->in.base.phys0 = run->in_phys;
1400 	ctx->out.base.phys0 = run->out_phys;
1401 
1402 	ctx->cur_buf_num = 0;
1403 	ctx->next_tile = 1;
1404 
1405 	/* remove run from pending_q and set as current */
1406 	list_del(&run->list);
1407 	chan->current_run = run;
1408 
1409 	return convert_start(run, 0);
1410 }
1411 
1412 /* hold irqlock when calling */
1413 static void run_next(struct ipu_image_convert_chan *chan)
1414 {
1415 	struct ipu_image_convert_priv *priv = chan->priv;
1416 	struct ipu_image_convert_run *run, *tmp;
1417 	int ret;
1418 
1419 	lockdep_assert_held(&chan->irqlock);
1420 
1421 	list_for_each_entry_safe(run, tmp, &chan->pending_q, list) {
1422 		/* skip contexts that are aborting */
1423 		if (run->ctx->aborting) {
1424 			dev_dbg(priv->ipu->dev,
1425 				"%s: task %u: skipping aborting ctx %p run %p\n",
1426 				__func__, chan->ic_task, run->ctx, run);
1427 			continue;
1428 		}
1429 
1430 		ret = do_run(run);
1431 		if (!ret)
1432 			break;
1433 
1434 		/*
1435 		 * something went wrong with start, add the run
1436 		 * to done q and continue to the next run in the
1437 		 * pending q.
1438 		 */
1439 		run->status = ret;
1440 		list_add_tail(&run->list, &chan->done_q);
1441 		chan->current_run = NULL;
1442 	}
1443 }
1444 
1445 static void empty_done_q(struct ipu_image_convert_chan *chan)
1446 {
1447 	struct ipu_image_convert_priv *priv = chan->priv;
1448 	struct ipu_image_convert_run *run;
1449 	unsigned long flags;
1450 
1451 	spin_lock_irqsave(&chan->irqlock, flags);
1452 
1453 	while (!list_empty(&chan->done_q)) {
1454 		run = list_entry(chan->done_q.next,
1455 				 struct ipu_image_convert_run,
1456 				 list);
1457 
1458 		list_del(&run->list);
1459 
1460 		dev_dbg(priv->ipu->dev,
1461 			"%s: task %u: completing ctx %p run %p with %d\n",
1462 			__func__, chan->ic_task, run->ctx, run, run->status);
1463 
1464 		/* call the completion callback and free the run */
1465 		spin_unlock_irqrestore(&chan->irqlock, flags);
1466 		run->ctx->complete(run, run->ctx->complete_context);
1467 		spin_lock_irqsave(&chan->irqlock, flags);
1468 	}
1469 
1470 	spin_unlock_irqrestore(&chan->irqlock, flags);
1471 }
1472 
1473 /*
1474  * the bottom half thread clears out the done_q, calling the
1475  * completion handler for each.
1476  */
1477 static irqreturn_t do_bh(int irq, void *dev_id)
1478 {
1479 	struct ipu_image_convert_chan *chan = dev_id;
1480 	struct ipu_image_convert_priv *priv = chan->priv;
1481 	struct ipu_image_convert_ctx *ctx;
1482 	unsigned long flags;
1483 
1484 	dev_dbg(priv->ipu->dev, "%s: task %u: enter\n", __func__,
1485 		chan->ic_task);
1486 
1487 	empty_done_q(chan);
1488 
1489 	spin_lock_irqsave(&chan->irqlock, flags);
1490 
1491 	/*
1492 	 * the done_q is cleared out, signal any contexts
1493 	 * that are aborting that abort can complete.
1494 	 */
1495 	list_for_each_entry(ctx, &chan->ctx_list, list) {
1496 		if (ctx->aborting) {
1497 			dev_dbg(priv->ipu->dev,
1498 				"%s: task %u: signaling abort for ctx %p\n",
1499 				__func__, chan->ic_task, ctx);
1500 			complete_all(&ctx->aborted);
1501 		}
1502 	}
1503 
1504 	spin_unlock_irqrestore(&chan->irqlock, flags);
1505 
1506 	dev_dbg(priv->ipu->dev, "%s: task %u: exit\n", __func__,
1507 		chan->ic_task);
1508 
1509 	return IRQ_HANDLED;
1510 }
1511 
1512 static bool ic_settings_changed(struct ipu_image_convert_ctx *ctx)
1513 {
1514 	unsigned int cur_tile = ctx->next_tile - 1;
1515 	unsigned int next_tile = ctx->next_tile;
1516 
1517 	if (ctx->resize_coeffs_h[cur_tile % ctx->in.num_cols] !=
1518 	    ctx->resize_coeffs_h[next_tile % ctx->in.num_cols] ||
1519 	    ctx->resize_coeffs_v[cur_tile / ctx->in.num_cols] !=
1520 	    ctx->resize_coeffs_v[next_tile / ctx->in.num_cols] ||
1521 	    ctx->in.tile[cur_tile].width != ctx->in.tile[next_tile].width ||
1522 	    ctx->in.tile[cur_tile].height != ctx->in.tile[next_tile].height ||
1523 	    ctx->out.tile[cur_tile].width != ctx->out.tile[next_tile].width ||
1524 	    ctx->out.tile[cur_tile].height != ctx->out.tile[next_tile].height)
1525 		return true;
1526 
1527 	return false;
1528 }
1529 
1530 /* hold irqlock when calling */
1531 static irqreturn_t do_irq(struct ipu_image_convert_run *run)
1532 {
1533 	struct ipu_image_convert_ctx *ctx = run->ctx;
1534 	struct ipu_image_convert_chan *chan = ctx->chan;
1535 	struct ipu_image_tile *src_tile, *dst_tile;
1536 	struct ipu_image_convert_image *s_image = &ctx->in;
1537 	struct ipu_image_convert_image *d_image = &ctx->out;
1538 	struct ipuv3_channel *outch;
1539 	unsigned int dst_idx;
1540 
1541 	lockdep_assert_held(&chan->irqlock);
1542 
1543 	outch = ipu_rot_mode_is_irt(ctx->rot_mode) ?
1544 		chan->rotation_out_chan : chan->out_chan;
1545 
1546 	/*
1547 	 * It is difficult to stop the channel DMA before the channels
1548 	 * enter the paused state. Without double-buffering the channels
1549 	 * are always in a paused state when the EOF irq occurs, so it
1550 	 * is safe to stop the channels now. For double-buffering we
1551 	 * just ignore the abort until the operation completes, when it
1552 	 * is safe to shut down.
1553 	 */
1554 	if (ctx->aborting && !ctx->double_buffering) {
1555 		convert_stop(run);
1556 		run->status = -EIO;
1557 		goto done;
1558 	}
1559 
1560 	if (ctx->next_tile == ctx->num_tiles) {
1561 		/*
1562 		 * the conversion is complete
1563 		 */
1564 		convert_stop(run);
1565 		run->status = 0;
1566 		goto done;
1567 	}
1568 
1569 	/*
1570 	 * not done, place the next tile buffers.
1571 	 */
1572 	if (!ctx->double_buffering) {
1573 		if (ic_settings_changed(ctx)) {
1574 			convert_stop(run);
1575 			convert_start(run, ctx->next_tile);
1576 		} else {
1577 			src_tile = &s_image->tile[ctx->next_tile];
1578 			dst_idx = ctx->out_tile_map[ctx->next_tile];
1579 			dst_tile = &d_image->tile[dst_idx];
1580 
1581 			ipu_cpmem_set_buffer(chan->in_chan, 0,
1582 					     s_image->base.phys0 +
1583 					     src_tile->offset);
1584 			ipu_cpmem_set_buffer(outch, 0,
1585 					     d_image->base.phys0 +
1586 					     dst_tile->offset);
1587 			if (s_image->fmt->planar)
1588 				ipu_cpmem_set_uv_offset(chan->in_chan,
1589 							src_tile->u_off,
1590 							src_tile->v_off);
1591 			if (d_image->fmt->planar)
1592 				ipu_cpmem_set_uv_offset(outch,
1593 							dst_tile->u_off,
1594 							dst_tile->v_off);
1595 
1596 			ipu_idmac_select_buffer(chan->in_chan, 0);
1597 			ipu_idmac_select_buffer(outch, 0);
1598 		}
1599 	} else if (ctx->next_tile < ctx->num_tiles - 1) {
1600 
1601 		src_tile = &s_image->tile[ctx->next_tile + 1];
1602 		dst_idx = ctx->out_tile_map[ctx->next_tile + 1];
1603 		dst_tile = &d_image->tile[dst_idx];
1604 
1605 		ipu_cpmem_set_buffer(chan->in_chan, ctx->cur_buf_num,
1606 				     s_image->base.phys0 + src_tile->offset);
1607 		ipu_cpmem_set_buffer(outch, ctx->cur_buf_num,
1608 				     d_image->base.phys0 + dst_tile->offset);
1609 
1610 		ipu_idmac_select_buffer(chan->in_chan, ctx->cur_buf_num);
1611 		ipu_idmac_select_buffer(outch, ctx->cur_buf_num);
1612 
1613 		ctx->cur_buf_num ^= 1;
1614 	}
1615 
1616 	ctx->next_tile++;
1617 	return IRQ_HANDLED;
1618 done:
1619 	list_add_tail(&run->list, &chan->done_q);
1620 	chan->current_run = NULL;
1621 	run_next(chan);
1622 	return IRQ_WAKE_THREAD;
1623 }
1624 
1625 static irqreturn_t norotate_irq(int irq, void *data)
1626 {
1627 	struct ipu_image_convert_chan *chan = data;
1628 	struct ipu_image_convert_ctx *ctx;
1629 	struct ipu_image_convert_run *run;
1630 	unsigned long flags;
1631 	irqreturn_t ret;
1632 
1633 	spin_lock_irqsave(&chan->irqlock, flags);
1634 
1635 	/* get current run and its context */
1636 	run = chan->current_run;
1637 	if (!run) {
1638 		ret = IRQ_NONE;
1639 		goto out;
1640 	}
1641 
1642 	ctx = run->ctx;
1643 
1644 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
1645 		/* this is a rotation operation, just ignore */
1646 		spin_unlock_irqrestore(&chan->irqlock, flags);
1647 		return IRQ_HANDLED;
1648 	}
1649 
1650 	ret = do_irq(run);
1651 out:
1652 	spin_unlock_irqrestore(&chan->irqlock, flags);
1653 	return ret;
1654 }
1655 
1656 static irqreturn_t rotate_irq(int irq, void *data)
1657 {
1658 	struct ipu_image_convert_chan *chan = data;
1659 	struct ipu_image_convert_priv *priv = chan->priv;
1660 	struct ipu_image_convert_ctx *ctx;
1661 	struct ipu_image_convert_run *run;
1662 	unsigned long flags;
1663 	irqreturn_t ret;
1664 
1665 	spin_lock_irqsave(&chan->irqlock, flags);
1666 
1667 	/* get current run and its context */
1668 	run = chan->current_run;
1669 	if (!run) {
1670 		ret = IRQ_NONE;
1671 		goto out;
1672 	}
1673 
1674 	ctx = run->ctx;
1675 
1676 	if (!ipu_rot_mode_is_irt(ctx->rot_mode)) {
1677 		/* this was NOT a rotation operation, shouldn't happen */
1678 		dev_err(priv->ipu->dev, "Unexpected rotation interrupt\n");
1679 		spin_unlock_irqrestore(&chan->irqlock, flags);
1680 		return IRQ_HANDLED;
1681 	}
1682 
1683 	ret = do_irq(run);
1684 out:
1685 	spin_unlock_irqrestore(&chan->irqlock, flags);
1686 	return ret;
1687 }
1688 
1689 /*
1690  * try to force the completion of runs for this ctx. Called when
1691  * abort wait times out in ipu_image_convert_abort().
1692  */
1693 static void force_abort(struct ipu_image_convert_ctx *ctx)
1694 {
1695 	struct ipu_image_convert_chan *chan = ctx->chan;
1696 	struct ipu_image_convert_run *run;
1697 	unsigned long flags;
1698 
1699 	spin_lock_irqsave(&chan->irqlock, flags);
1700 
1701 	run = chan->current_run;
1702 	if (run && run->ctx == ctx) {
1703 		convert_stop(run);
1704 		run->status = -EIO;
1705 		list_add_tail(&run->list, &chan->done_q);
1706 		chan->current_run = NULL;
1707 		run_next(chan);
1708 	}
1709 
1710 	spin_unlock_irqrestore(&chan->irqlock, flags);
1711 
1712 	empty_done_q(chan);
1713 }
1714 
1715 static void release_ipu_resources(struct ipu_image_convert_chan *chan)
1716 {
1717 	if (chan->out_eof_irq >= 0)
1718 		free_irq(chan->out_eof_irq, chan);
1719 	if (chan->rot_out_eof_irq >= 0)
1720 		free_irq(chan->rot_out_eof_irq, chan);
1721 
1722 	if (!IS_ERR_OR_NULL(chan->in_chan))
1723 		ipu_idmac_put(chan->in_chan);
1724 	if (!IS_ERR_OR_NULL(chan->out_chan))
1725 		ipu_idmac_put(chan->out_chan);
1726 	if (!IS_ERR_OR_NULL(chan->rotation_in_chan))
1727 		ipu_idmac_put(chan->rotation_in_chan);
1728 	if (!IS_ERR_OR_NULL(chan->rotation_out_chan))
1729 		ipu_idmac_put(chan->rotation_out_chan);
1730 	if (!IS_ERR_OR_NULL(chan->ic))
1731 		ipu_ic_put(chan->ic);
1732 
1733 	chan->in_chan = chan->out_chan = chan->rotation_in_chan =
1734 		chan->rotation_out_chan = NULL;
1735 	chan->out_eof_irq = chan->rot_out_eof_irq = -1;
1736 }
1737 
1738 static int get_ipu_resources(struct ipu_image_convert_chan *chan)
1739 {
1740 	const struct ipu_image_convert_dma_chan *dma = chan->dma_ch;
1741 	struct ipu_image_convert_priv *priv = chan->priv;
1742 	int ret;
1743 
1744 	/* get IC */
1745 	chan->ic = ipu_ic_get(priv->ipu, chan->ic_task);
1746 	if (IS_ERR(chan->ic)) {
1747 		dev_err(priv->ipu->dev, "could not acquire IC\n");
1748 		ret = PTR_ERR(chan->ic);
1749 		goto err;
1750 	}
1751 
1752 	/* get IDMAC channels */
1753 	chan->in_chan = ipu_idmac_get(priv->ipu, dma->in);
1754 	chan->out_chan = ipu_idmac_get(priv->ipu, dma->out);
1755 	if (IS_ERR(chan->in_chan) || IS_ERR(chan->out_chan)) {
1756 		dev_err(priv->ipu->dev, "could not acquire idmac channels\n");
1757 		ret = -EBUSY;
1758 		goto err;
1759 	}
1760 
1761 	chan->rotation_in_chan = ipu_idmac_get(priv->ipu, dma->rot_in);
1762 	chan->rotation_out_chan = ipu_idmac_get(priv->ipu, dma->rot_out);
1763 	if (IS_ERR(chan->rotation_in_chan) || IS_ERR(chan->rotation_out_chan)) {
1764 		dev_err(priv->ipu->dev,
1765 			"could not acquire idmac rotation channels\n");
1766 		ret = -EBUSY;
1767 		goto err;
1768 	}
1769 
1770 	/* acquire the EOF interrupts */
1771 	chan->out_eof_irq = ipu_idmac_channel_irq(priv->ipu,
1772 						  chan->out_chan,
1773 						  IPU_IRQ_EOF);
1774 
1775 	ret = request_threaded_irq(chan->out_eof_irq, norotate_irq, do_bh,
1776 				   0, "ipu-ic", chan);
1777 	if (ret < 0) {
1778 		dev_err(priv->ipu->dev, "could not acquire irq %d\n",
1779 			 chan->out_eof_irq);
1780 		chan->out_eof_irq = -1;
1781 		goto err;
1782 	}
1783 
1784 	chan->rot_out_eof_irq = ipu_idmac_channel_irq(priv->ipu,
1785 						     chan->rotation_out_chan,
1786 						     IPU_IRQ_EOF);
1787 
1788 	ret = request_threaded_irq(chan->rot_out_eof_irq, rotate_irq, do_bh,
1789 				   0, "ipu-ic", chan);
1790 	if (ret < 0) {
1791 		dev_err(priv->ipu->dev, "could not acquire irq %d\n",
1792 			chan->rot_out_eof_irq);
1793 		chan->rot_out_eof_irq = -1;
1794 		goto err;
1795 	}
1796 
1797 	return 0;
1798 err:
1799 	release_ipu_resources(chan);
1800 	return ret;
1801 }
1802 
1803 static int fill_image(struct ipu_image_convert_ctx *ctx,
1804 		      struct ipu_image_convert_image *ic_image,
1805 		      struct ipu_image *image,
1806 		      enum ipu_image_convert_type type)
1807 {
1808 	struct ipu_image_convert_priv *priv = ctx->chan->priv;
1809 
1810 	ic_image->base = *image;
1811 	ic_image->type = type;
1812 
1813 	ic_image->fmt = get_format(image->pix.pixelformat);
1814 	if (!ic_image->fmt) {
1815 		dev_err(priv->ipu->dev, "pixelformat not supported for %s\n",
1816 			type == IMAGE_CONVERT_OUT ? "Output" : "Input");
1817 		return -EINVAL;
1818 	}
1819 
1820 	if (ic_image->fmt->planar)
1821 		ic_image->stride = ic_image->base.pix.width;
1822 	else
1823 		ic_image->stride  = ic_image->base.pix.bytesperline;
1824 
1825 	return 0;
1826 }
1827 
1828 /* borrowed from drivers/media/v4l2-core/v4l2-common.c */
1829 static unsigned int clamp_align(unsigned int x, unsigned int min,
1830 				unsigned int max, unsigned int align)
1831 {
1832 	/* Bits that must be zero to be aligned */
1833 	unsigned int mask = ~((1 << align) - 1);
1834 
1835 	/* Clamp to aligned min and max */
1836 	x = clamp(x, (min + ~mask) & mask, max & mask);
1837 
1838 	/* Round to nearest aligned value */
1839 	if (align)
1840 		x = (x + (1 << (align - 1))) & mask;
1841 
1842 	return x;
1843 }
1844 
1845 /* Adjusts input/output images to IPU restrictions */
1846 void ipu_image_convert_adjust(struct ipu_image *in, struct ipu_image *out,
1847 			      enum ipu_rotate_mode rot_mode)
1848 {
1849 	const struct ipu_image_pixfmt *infmt, *outfmt;
1850 	unsigned int num_in_rows, num_in_cols;
1851 	unsigned int num_out_rows, num_out_cols;
1852 	u32 w_align, h_align;
1853 
1854 	infmt = get_format(in->pix.pixelformat);
1855 	outfmt = get_format(out->pix.pixelformat);
1856 
1857 	/* set some default pixel formats if needed */
1858 	if (!infmt) {
1859 		in->pix.pixelformat = V4L2_PIX_FMT_RGB24;
1860 		infmt = get_format(V4L2_PIX_FMT_RGB24);
1861 	}
1862 	if (!outfmt) {
1863 		out->pix.pixelformat = V4L2_PIX_FMT_RGB24;
1864 		outfmt = get_format(V4L2_PIX_FMT_RGB24);
1865 	}
1866 
1867 	/* image converter does not handle fields */
1868 	in->pix.field = out->pix.field = V4L2_FIELD_NONE;
1869 
1870 	/* resizer cannot downsize more than 4:1 */
1871 	if (ipu_rot_mode_is_irt(rot_mode)) {
1872 		out->pix.height = max_t(__u32, out->pix.height,
1873 					in->pix.width / 4);
1874 		out->pix.width = max_t(__u32, out->pix.width,
1875 				       in->pix.height / 4);
1876 	} else {
1877 		out->pix.width = max_t(__u32, out->pix.width,
1878 				       in->pix.width / 4);
1879 		out->pix.height = max_t(__u32, out->pix.height,
1880 					in->pix.height / 4);
1881 	}
1882 
1883 	/* get tiling rows/cols from output format */
1884 	num_out_rows = num_stripes(out->pix.height);
1885 	num_out_cols = num_stripes(out->pix.width);
1886 	if (ipu_rot_mode_is_irt(rot_mode)) {
1887 		num_in_rows = num_out_cols;
1888 		num_in_cols = num_out_rows;
1889 	} else {
1890 		num_in_rows = num_out_rows;
1891 		num_in_cols = num_out_cols;
1892 	}
1893 
1894 	/* align input width/height */
1895 	w_align = ilog2(tile_width_align(infmt) * num_in_cols);
1896 	h_align = ilog2(tile_height_align(IMAGE_CONVERT_IN, rot_mode) *
1897 			num_in_rows);
1898 	in->pix.width = clamp_align(in->pix.width, MIN_W, MAX_W, w_align);
1899 	in->pix.height = clamp_align(in->pix.height, MIN_H, MAX_H, h_align);
1900 
1901 	/* align output width/height */
1902 	w_align = ilog2(tile_width_align(outfmt) * num_out_cols);
1903 	h_align = ilog2(tile_height_align(IMAGE_CONVERT_OUT, rot_mode) *
1904 			num_out_rows);
1905 	out->pix.width = clamp_align(out->pix.width, MIN_W, MAX_W, w_align);
1906 	out->pix.height = clamp_align(out->pix.height, MIN_H, MAX_H, h_align);
1907 
1908 	/* set input/output strides and image sizes */
1909 	in->pix.bytesperline = (in->pix.width * infmt->bpp) >> 3;
1910 	in->pix.sizeimage = in->pix.height * in->pix.bytesperline;
1911 	out->pix.bytesperline = (out->pix.width * outfmt->bpp) >> 3;
1912 	out->pix.sizeimage = out->pix.height * out->pix.bytesperline;
1913 }
1914 EXPORT_SYMBOL_GPL(ipu_image_convert_adjust);
1915 
1916 /*
1917  * this is used by ipu_image_convert_prepare() to verify set input and
1918  * output images are valid before starting the conversion. Clients can
1919  * also call it before calling ipu_image_convert_prepare().
1920  */
1921 int ipu_image_convert_verify(struct ipu_image *in, struct ipu_image *out,
1922 			     enum ipu_rotate_mode rot_mode)
1923 {
1924 	struct ipu_image testin, testout;
1925 
1926 	testin = *in;
1927 	testout = *out;
1928 
1929 	ipu_image_convert_adjust(&testin, &testout, rot_mode);
1930 
1931 	if (testin.pix.width != in->pix.width ||
1932 	    testin.pix.height != in->pix.height ||
1933 	    testout.pix.width != out->pix.width ||
1934 	    testout.pix.height != out->pix.height)
1935 		return -EINVAL;
1936 
1937 	return 0;
1938 }
1939 EXPORT_SYMBOL_GPL(ipu_image_convert_verify);
1940 
1941 /*
1942  * Call ipu_image_convert_prepare() to prepare for the conversion of
1943  * given images and rotation mode. Returns a new conversion context.
1944  */
1945 struct ipu_image_convert_ctx *
1946 ipu_image_convert_prepare(struct ipu_soc *ipu, enum ipu_ic_task ic_task,
1947 			  struct ipu_image *in, struct ipu_image *out,
1948 			  enum ipu_rotate_mode rot_mode,
1949 			  ipu_image_convert_cb_t complete,
1950 			  void *complete_context)
1951 {
1952 	struct ipu_image_convert_priv *priv = ipu->image_convert_priv;
1953 	struct ipu_image_convert_image *s_image, *d_image;
1954 	struct ipu_image_convert_chan *chan;
1955 	struct ipu_image_convert_ctx *ctx;
1956 	unsigned long flags;
1957 	bool get_res;
1958 	int ret;
1959 
1960 	if (!in || !out || !complete ||
1961 	    (ic_task != IC_TASK_VIEWFINDER &&
1962 	     ic_task != IC_TASK_POST_PROCESSOR))
1963 		return ERR_PTR(-EINVAL);
1964 
1965 	/* verify the in/out images before continuing */
1966 	ret = ipu_image_convert_verify(in, out, rot_mode);
1967 	if (ret) {
1968 		dev_err(priv->ipu->dev, "%s: in/out formats invalid\n",
1969 			__func__);
1970 		return ERR_PTR(ret);
1971 	}
1972 
1973 	chan = &priv->chan[ic_task];
1974 
1975 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1976 	if (!ctx)
1977 		return ERR_PTR(-ENOMEM);
1978 
1979 	dev_dbg(priv->ipu->dev, "%s: task %u: ctx %p\n", __func__,
1980 		chan->ic_task, ctx);
1981 
1982 	ctx->chan = chan;
1983 	init_completion(&ctx->aborted);
1984 
1985 	s_image = &ctx->in;
1986 	d_image = &ctx->out;
1987 
1988 	/* set tiling and rotation */
1989 	d_image->num_rows = num_stripes(out->pix.height);
1990 	d_image->num_cols = num_stripes(out->pix.width);
1991 	if (ipu_rot_mode_is_irt(rot_mode)) {
1992 		s_image->num_rows = d_image->num_cols;
1993 		s_image->num_cols = d_image->num_rows;
1994 	} else {
1995 		s_image->num_rows = d_image->num_rows;
1996 		s_image->num_cols = d_image->num_cols;
1997 	}
1998 
1999 	ctx->num_tiles = d_image->num_cols * d_image->num_rows;
2000 	ctx->rot_mode = rot_mode;
2001 
2002 	ret = fill_image(ctx, s_image, in, IMAGE_CONVERT_IN);
2003 	if (ret)
2004 		goto out_free;
2005 	ret = fill_image(ctx, d_image, out, IMAGE_CONVERT_OUT);
2006 	if (ret)
2007 		goto out_free;
2008 
2009 	ret = calc_image_resize_coefficients(ctx, in, out);
2010 	if (ret)
2011 		goto out_free;
2012 
2013 	calc_out_tile_map(ctx);
2014 
2015 	find_seams(ctx, s_image, d_image);
2016 
2017 	calc_tile_dimensions(ctx, s_image);
2018 	ret = calc_tile_offsets(ctx, s_image);
2019 	if (ret)
2020 		goto out_free;
2021 
2022 	calc_tile_dimensions(ctx, d_image);
2023 	ret = calc_tile_offsets(ctx, d_image);
2024 	if (ret)
2025 		goto out_free;
2026 
2027 	calc_tile_resize_coefficients(ctx);
2028 
2029 	dump_format(ctx, s_image);
2030 	dump_format(ctx, d_image);
2031 
2032 	ctx->complete = complete;
2033 	ctx->complete_context = complete_context;
2034 
2035 	/*
2036 	 * Can we use double-buffering for this operation? If there is
2037 	 * only one tile (the whole image can be converted in a single
2038 	 * operation) there's no point in using double-buffering. Also,
2039 	 * the IPU's IDMAC channels allow only a single U and V plane
2040 	 * offset shared between both buffers, but these offsets change
2041 	 * for every tile, and therefore would have to be updated for
2042 	 * each buffer which is not possible. So double-buffering is
2043 	 * impossible when either the source or destination images are
2044 	 * a planar format (YUV420, YUV422P, etc.).
2045 	 */
2046 	ctx->double_buffering = (ctx->num_tiles > 1 &&
2047 				 !s_image->fmt->planar &&
2048 				 !d_image->fmt->planar);
2049 
2050 	if (ipu_rot_mode_is_irt(ctx->rot_mode)) {
2051 		unsigned long intermediate_size = d_image->tile[0].size;
2052 		unsigned int i;
2053 
2054 		for (i = 1; i < ctx->num_tiles; i++) {
2055 			if (d_image->tile[i].size > intermediate_size)
2056 				intermediate_size = d_image->tile[i].size;
2057 		}
2058 
2059 		ret = alloc_dma_buf(priv, &ctx->rot_intermediate[0],
2060 				    intermediate_size);
2061 		if (ret)
2062 			goto out_free;
2063 		if (ctx->double_buffering) {
2064 			ret = alloc_dma_buf(priv,
2065 					    &ctx->rot_intermediate[1],
2066 					    intermediate_size);
2067 			if (ret)
2068 				goto out_free_dmabuf0;
2069 		}
2070 	}
2071 
2072 	spin_lock_irqsave(&chan->irqlock, flags);
2073 
2074 	get_res = list_empty(&chan->ctx_list);
2075 
2076 	list_add_tail(&ctx->list, &chan->ctx_list);
2077 
2078 	spin_unlock_irqrestore(&chan->irqlock, flags);
2079 
2080 	if (get_res) {
2081 		ret = get_ipu_resources(chan);
2082 		if (ret)
2083 			goto out_free_dmabuf1;
2084 	}
2085 
2086 	return ctx;
2087 
2088 out_free_dmabuf1:
2089 	free_dma_buf(priv, &ctx->rot_intermediate[1]);
2090 	spin_lock_irqsave(&chan->irqlock, flags);
2091 	list_del(&ctx->list);
2092 	spin_unlock_irqrestore(&chan->irqlock, flags);
2093 out_free_dmabuf0:
2094 	free_dma_buf(priv, &ctx->rot_intermediate[0]);
2095 out_free:
2096 	kfree(ctx);
2097 	return ERR_PTR(ret);
2098 }
2099 EXPORT_SYMBOL_GPL(ipu_image_convert_prepare);
2100 
2101 /*
2102  * Carry out a single image conversion run. Only the physaddr's of the input
2103  * and output image buffers are needed. The conversion context must have
2104  * been created previously with ipu_image_convert_prepare().
2105  */
2106 int ipu_image_convert_queue(struct ipu_image_convert_run *run)
2107 {
2108 	struct ipu_image_convert_chan *chan;
2109 	struct ipu_image_convert_priv *priv;
2110 	struct ipu_image_convert_ctx *ctx;
2111 	unsigned long flags;
2112 	int ret = 0;
2113 
2114 	if (!run || !run->ctx || !run->in_phys || !run->out_phys)
2115 		return -EINVAL;
2116 
2117 	ctx = run->ctx;
2118 	chan = ctx->chan;
2119 	priv = chan->priv;
2120 
2121 	dev_dbg(priv->ipu->dev, "%s: task %u: ctx %p run %p\n", __func__,
2122 		chan->ic_task, ctx, run);
2123 
2124 	INIT_LIST_HEAD(&run->list);
2125 
2126 	spin_lock_irqsave(&chan->irqlock, flags);
2127 
2128 	if (ctx->aborting) {
2129 		ret = -EIO;
2130 		goto unlock;
2131 	}
2132 
2133 	list_add_tail(&run->list, &chan->pending_q);
2134 
2135 	if (!chan->current_run) {
2136 		ret = do_run(run);
2137 		if (ret)
2138 			chan->current_run = NULL;
2139 	}
2140 unlock:
2141 	spin_unlock_irqrestore(&chan->irqlock, flags);
2142 	return ret;
2143 }
2144 EXPORT_SYMBOL_GPL(ipu_image_convert_queue);
2145 
2146 /* Abort any active or pending conversions for this context */
2147 static void __ipu_image_convert_abort(struct ipu_image_convert_ctx *ctx)
2148 {
2149 	struct ipu_image_convert_chan *chan = ctx->chan;
2150 	struct ipu_image_convert_priv *priv = chan->priv;
2151 	struct ipu_image_convert_run *run, *active_run, *tmp;
2152 	unsigned long flags;
2153 	int run_count, ret;
2154 
2155 	spin_lock_irqsave(&chan->irqlock, flags);
2156 
2157 	/* move all remaining pending runs in this context to done_q */
2158 	list_for_each_entry_safe(run, tmp, &chan->pending_q, list) {
2159 		if (run->ctx != ctx)
2160 			continue;
2161 		run->status = -EIO;
2162 		list_move_tail(&run->list, &chan->done_q);
2163 	}
2164 
2165 	run_count = get_run_count(ctx, &chan->done_q);
2166 	active_run = (chan->current_run && chan->current_run->ctx == ctx) ?
2167 		chan->current_run : NULL;
2168 
2169 	if (active_run)
2170 		reinit_completion(&ctx->aborted);
2171 
2172 	ctx->aborting = true;
2173 
2174 	spin_unlock_irqrestore(&chan->irqlock, flags);
2175 
2176 	if (!run_count && !active_run) {
2177 		dev_dbg(priv->ipu->dev,
2178 			"%s: task %u: no abort needed for ctx %p\n",
2179 			__func__, chan->ic_task, ctx);
2180 		return;
2181 	}
2182 
2183 	if (!active_run) {
2184 		empty_done_q(chan);
2185 		return;
2186 	}
2187 
2188 	dev_dbg(priv->ipu->dev,
2189 		"%s: task %u: wait for completion: %d runs\n",
2190 		__func__, chan->ic_task, run_count);
2191 
2192 	ret = wait_for_completion_timeout(&ctx->aborted,
2193 					  msecs_to_jiffies(10000));
2194 	if (ret == 0) {
2195 		dev_warn(priv->ipu->dev, "%s: timeout\n", __func__);
2196 		force_abort(ctx);
2197 	}
2198 }
2199 
2200 void ipu_image_convert_abort(struct ipu_image_convert_ctx *ctx)
2201 {
2202 	__ipu_image_convert_abort(ctx);
2203 	ctx->aborting = false;
2204 }
2205 EXPORT_SYMBOL_GPL(ipu_image_convert_abort);
2206 
2207 /* Unprepare image conversion context */
2208 void ipu_image_convert_unprepare(struct ipu_image_convert_ctx *ctx)
2209 {
2210 	struct ipu_image_convert_chan *chan = ctx->chan;
2211 	struct ipu_image_convert_priv *priv = chan->priv;
2212 	unsigned long flags;
2213 	bool put_res;
2214 
2215 	/* make sure no runs are hanging around */
2216 	__ipu_image_convert_abort(ctx);
2217 
2218 	dev_dbg(priv->ipu->dev, "%s: task %u: removing ctx %p\n", __func__,
2219 		chan->ic_task, ctx);
2220 
2221 	spin_lock_irqsave(&chan->irqlock, flags);
2222 
2223 	list_del(&ctx->list);
2224 
2225 	put_res = list_empty(&chan->ctx_list);
2226 
2227 	spin_unlock_irqrestore(&chan->irqlock, flags);
2228 
2229 	if (put_res)
2230 		release_ipu_resources(chan);
2231 
2232 	free_dma_buf(priv, &ctx->rot_intermediate[1]);
2233 	free_dma_buf(priv, &ctx->rot_intermediate[0]);
2234 
2235 	kfree(ctx);
2236 }
2237 EXPORT_SYMBOL_GPL(ipu_image_convert_unprepare);
2238 
2239 /*
2240  * "Canned" asynchronous single image conversion. Allocates and returns
2241  * a new conversion run.  On successful return the caller must free the
2242  * run and call ipu_image_convert_unprepare() after conversion completes.
2243  */
2244 struct ipu_image_convert_run *
2245 ipu_image_convert(struct ipu_soc *ipu, enum ipu_ic_task ic_task,
2246 		  struct ipu_image *in, struct ipu_image *out,
2247 		  enum ipu_rotate_mode rot_mode,
2248 		  ipu_image_convert_cb_t complete,
2249 		  void *complete_context)
2250 {
2251 	struct ipu_image_convert_ctx *ctx;
2252 	struct ipu_image_convert_run *run;
2253 	int ret;
2254 
2255 	ctx = ipu_image_convert_prepare(ipu, ic_task, in, out, rot_mode,
2256 					complete, complete_context);
2257 	if (IS_ERR(ctx))
2258 		return ERR_CAST(ctx);
2259 
2260 	run = kzalloc(sizeof(*run), GFP_KERNEL);
2261 	if (!run) {
2262 		ipu_image_convert_unprepare(ctx);
2263 		return ERR_PTR(-ENOMEM);
2264 	}
2265 
2266 	run->ctx = ctx;
2267 	run->in_phys = in->phys0;
2268 	run->out_phys = out->phys0;
2269 
2270 	ret = ipu_image_convert_queue(run);
2271 	if (ret) {
2272 		ipu_image_convert_unprepare(ctx);
2273 		kfree(run);
2274 		return ERR_PTR(ret);
2275 	}
2276 
2277 	return run;
2278 }
2279 EXPORT_SYMBOL_GPL(ipu_image_convert);
2280 
2281 /* "Canned" synchronous single image conversion */
2282 static void image_convert_sync_complete(struct ipu_image_convert_run *run,
2283 					void *data)
2284 {
2285 	struct completion *comp = data;
2286 
2287 	complete(comp);
2288 }
2289 
2290 int ipu_image_convert_sync(struct ipu_soc *ipu, enum ipu_ic_task ic_task,
2291 			   struct ipu_image *in, struct ipu_image *out,
2292 			   enum ipu_rotate_mode rot_mode)
2293 {
2294 	struct ipu_image_convert_run *run;
2295 	struct completion comp;
2296 	int ret;
2297 
2298 	init_completion(&comp);
2299 
2300 	run = ipu_image_convert(ipu, ic_task, in, out, rot_mode,
2301 				image_convert_sync_complete, &comp);
2302 	if (IS_ERR(run))
2303 		return PTR_ERR(run);
2304 
2305 	ret = wait_for_completion_timeout(&comp, msecs_to_jiffies(10000));
2306 	ret = (ret == 0) ? -ETIMEDOUT : 0;
2307 
2308 	ipu_image_convert_unprepare(run->ctx);
2309 	kfree(run);
2310 
2311 	return ret;
2312 }
2313 EXPORT_SYMBOL_GPL(ipu_image_convert_sync);
2314 
2315 int ipu_image_convert_init(struct ipu_soc *ipu, struct device *dev)
2316 {
2317 	struct ipu_image_convert_priv *priv;
2318 	int i;
2319 
2320 	priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
2321 	if (!priv)
2322 		return -ENOMEM;
2323 
2324 	ipu->image_convert_priv = priv;
2325 	priv->ipu = ipu;
2326 
2327 	for (i = 0; i < IC_NUM_TASKS; i++) {
2328 		struct ipu_image_convert_chan *chan = &priv->chan[i];
2329 
2330 		chan->ic_task = i;
2331 		chan->priv = priv;
2332 		chan->dma_ch = &image_convert_dma_chan[i];
2333 		chan->out_eof_irq = -1;
2334 		chan->rot_out_eof_irq = -1;
2335 
2336 		spin_lock_init(&chan->irqlock);
2337 		INIT_LIST_HEAD(&chan->ctx_list);
2338 		INIT_LIST_HEAD(&chan->pending_q);
2339 		INIT_LIST_HEAD(&chan->done_q);
2340 	}
2341 
2342 	return 0;
2343 }
2344 
2345 void ipu_image_convert_exit(struct ipu_soc *ipu)
2346 {
2347 }
2348