1 /*
2  * Copyright (C) 2010-2013 Bluecherry, LLC <http://www.bluecherrydvr.com>
3  *
4  * Original author:
5  * Ben Collins <bcollins@ubuntu.com>
6  *
7  * Additional work by:
8  * John Brooks <john.brooks@bluecherry.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  */
20 
21 #include <linux/kernel.h>
22 #include <linux/module.h>
23 #include <linux/kthread.h>
24 #include <linux/freezer.h>
25 
26 #include <media/v4l2-ioctl.h>
27 #include <media/v4l2-common.h>
28 #include <media/v4l2-event.h>
29 #include <media/videobuf2-dma-sg.h>
30 
31 #include "solo6x10.h"
32 #include "solo6x10-tw28.h"
33 #include "solo6x10-jpeg.h"
34 
35 #define MIN_VID_BUFFERS		2
36 #define FRAME_BUF_SIZE		(196 * 1024)
37 #define MP4_QS			16
38 #define DMA_ALIGN		4096
39 
40 /* 6010 M4V */
41 static unsigned char vop_6010_ntsc_d1[] = {
42 	0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20,
43 	0x02, 0x48, 0x1d, 0xc0, 0x00, 0x40, 0x00, 0x40,
44 	0x00, 0x40, 0x00, 0x80, 0x00, 0x97, 0x53, 0x04,
45 	0x1f, 0x4c, 0x58, 0x10, 0xf0, 0x71, 0x18, 0x3f,
46 };
47 
48 static unsigned char vop_6010_ntsc_cif[] = {
49 	0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20,
50 	0x02, 0x48, 0x1d, 0xc0, 0x00, 0x40, 0x00, 0x40,
51 	0x00, 0x40, 0x00, 0x80, 0x00, 0x97, 0x53, 0x04,
52 	0x1f, 0x4c, 0x2c, 0x10, 0x78, 0x51, 0x18, 0x3f,
53 };
54 
55 static unsigned char vop_6010_pal_d1[] = {
56 	0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20,
57 	0x02, 0x48, 0x15, 0xc0, 0x00, 0x40, 0x00, 0x40,
58 	0x00, 0x40, 0x00, 0x80, 0x00, 0x97, 0x53, 0x04,
59 	0x1f, 0x4c, 0x58, 0x11, 0x20, 0x71, 0x18, 0x3f,
60 };
61 
62 static unsigned char vop_6010_pal_cif[] = {
63 	0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20,
64 	0x02, 0x48, 0x15, 0xc0, 0x00, 0x40, 0x00, 0x40,
65 	0x00, 0x40, 0x00, 0x80, 0x00, 0x97, 0x53, 0x04,
66 	0x1f, 0x4c, 0x2c, 0x10, 0x90, 0x51, 0x18, 0x3f,
67 };
68 
69 /* 6110 h.264 */
70 static unsigned char vop_6110_ntsc_d1[] = {
71 	0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e,
72 	0x9a, 0x74, 0x05, 0x81, 0xec, 0x80, 0x00, 0x00,
73 	0x00, 0x01, 0x68, 0xce, 0x32, 0x28, 0x00, 0x00,
74 };
75 
76 static unsigned char vop_6110_ntsc_cif[] = {
77 	0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e,
78 	0x9a, 0x74, 0x0b, 0x0f, 0xc8, 0x00, 0x00, 0x00,
79 	0x01, 0x68, 0xce, 0x32, 0x28, 0x00, 0x00, 0x00,
80 };
81 
82 static unsigned char vop_6110_pal_d1[] = {
83 	0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e,
84 	0x9a, 0x74, 0x05, 0x80, 0x93, 0x20, 0x00, 0x00,
85 	0x00, 0x01, 0x68, 0xce, 0x32, 0x28, 0x00, 0x00,
86 };
87 
88 static unsigned char vop_6110_pal_cif[] = {
89 	0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e,
90 	0x9a, 0x74, 0x0b, 0x04, 0xb2, 0x00, 0x00, 0x00,
91 	0x01, 0x68, 0xce, 0x32, 0x28, 0x00, 0x00, 0x00,
92 };
93 
94 typedef __le32 vop_header[16];
95 
96 struct solo_enc_buf {
97 	enum solo_enc_types	type;
98 	const vop_header	*vh;
99 	int			motion;
100 };
101 
102 static int solo_is_motion_on(struct solo_enc_dev *solo_enc)
103 {
104 	struct solo_dev *solo_dev = solo_enc->solo_dev;
105 
106 	return (solo_dev->motion_mask >> solo_enc->ch) & 1;
107 }
108 
109 static int solo_motion_detected(struct solo_enc_dev *solo_enc)
110 {
111 	struct solo_dev *solo_dev = solo_enc->solo_dev;
112 	unsigned long flags;
113 	u32 ch_mask = 1 << solo_enc->ch;
114 	int ret = 0;
115 
116 	spin_lock_irqsave(&solo_enc->motion_lock, flags);
117 	if (solo_reg_read(solo_dev, SOLO_VI_MOT_STATUS) & ch_mask) {
118 		solo_reg_write(solo_dev, SOLO_VI_MOT_CLEAR, ch_mask);
119 		ret = 1;
120 	}
121 	spin_unlock_irqrestore(&solo_enc->motion_lock, flags);
122 
123 	return ret;
124 }
125 
126 static void solo_motion_toggle(struct solo_enc_dev *solo_enc, int on)
127 {
128 	struct solo_dev *solo_dev = solo_enc->solo_dev;
129 	u32 mask = 1 << solo_enc->ch;
130 	unsigned long flags;
131 
132 	spin_lock_irqsave(&solo_enc->motion_lock, flags);
133 
134 	if (on)
135 		solo_dev->motion_mask |= mask;
136 	else
137 		solo_dev->motion_mask &= ~mask;
138 
139 	solo_reg_write(solo_dev, SOLO_VI_MOT_CLEAR, mask);
140 
141 	solo_reg_write(solo_dev, SOLO_VI_MOT_ADR,
142 		       SOLO_VI_MOTION_EN(solo_dev->motion_mask) |
143 		       (SOLO_MOTION_EXT_ADDR(solo_dev) >> 16));
144 
145 	spin_unlock_irqrestore(&solo_enc->motion_lock, flags);
146 }
147 
148 void solo_update_mode(struct solo_enc_dev *solo_enc)
149 {
150 	struct solo_dev *solo_dev = solo_enc->solo_dev;
151 	int vop_len;
152 	unsigned char *vop;
153 
154 	solo_enc->interlaced = (solo_enc->mode & 0x08) ? 1 : 0;
155 	solo_enc->bw_weight = max(solo_dev->fps / solo_enc->interval, 1);
156 
157 	if (solo_enc->mode == SOLO_ENC_MODE_CIF) {
158 		solo_enc->width = solo_dev->video_hsize >> 1;
159 		solo_enc->height = solo_dev->video_vsize;
160 		if (solo_dev->type == SOLO_DEV_6110) {
161 			if (solo_dev->video_type == SOLO_VO_FMT_TYPE_NTSC) {
162 				vop = vop_6110_ntsc_cif;
163 				vop_len = sizeof(vop_6110_ntsc_cif);
164 			} else {
165 				vop = vop_6110_pal_cif;
166 				vop_len = sizeof(vop_6110_pal_cif);
167 			}
168 		} else {
169 			if (solo_dev->video_type == SOLO_VO_FMT_TYPE_NTSC) {
170 				vop = vop_6010_ntsc_cif;
171 				vop_len = sizeof(vop_6010_ntsc_cif);
172 			} else {
173 				vop = vop_6010_pal_cif;
174 				vop_len = sizeof(vop_6010_pal_cif);
175 			}
176 		}
177 	} else {
178 		solo_enc->width = solo_dev->video_hsize;
179 		solo_enc->height = solo_dev->video_vsize << 1;
180 		solo_enc->bw_weight <<= 2;
181 		if (solo_dev->type == SOLO_DEV_6110) {
182 			if (solo_dev->video_type == SOLO_VO_FMT_TYPE_NTSC) {
183 				vop = vop_6110_ntsc_d1;
184 				vop_len = sizeof(vop_6110_ntsc_d1);
185 			} else {
186 				vop = vop_6110_pal_d1;
187 				vop_len = sizeof(vop_6110_pal_d1);
188 			}
189 		} else {
190 			if (solo_dev->video_type == SOLO_VO_FMT_TYPE_NTSC) {
191 				vop = vop_6010_ntsc_d1;
192 				vop_len = sizeof(vop_6010_ntsc_d1);
193 			} else {
194 				vop = vop_6010_pal_d1;
195 				vop_len = sizeof(vop_6010_pal_d1);
196 			}
197 		}
198 	}
199 
200 	memcpy(solo_enc->vop, vop, vop_len);
201 
202 	/* Some fixups for 6010/M4V */
203 	if (solo_dev->type == SOLO_DEV_6010) {
204 		u16 fps = solo_dev->fps * 1000;
205 		u16 interval = solo_enc->interval * 1000;
206 
207 		vop = solo_enc->vop;
208 
209 		/* Frame rate and interval */
210 		vop[22] = fps >> 4;
211 		vop[23] = ((fps << 4) & 0xf0) | 0x0c
212 			| ((interval >> 13) & 0x3);
213 		vop[24] = (interval >> 5) & 0xff;
214 		vop[25] = ((interval << 3) & 0xf8) | 0x04;
215 	}
216 
217 	solo_enc->vop_len = vop_len;
218 
219 	/* Now handle the jpeg header */
220 	vop = solo_enc->jpeg_header;
221 	vop[SOF0_START + 5] = 0xff & (solo_enc->height >> 8);
222 	vop[SOF0_START + 6] = 0xff & solo_enc->height;
223 	vop[SOF0_START + 7] = 0xff & (solo_enc->width >> 8);
224 	vop[SOF0_START + 8] = 0xff & solo_enc->width;
225 
226 	memcpy(vop + DQT_START,
227 	       jpeg_dqt[solo_g_jpeg_qp(solo_dev, solo_enc->ch)], DQT_LEN);
228 }
229 
230 static int solo_enc_on(struct solo_enc_dev *solo_enc)
231 {
232 	u8 ch = solo_enc->ch;
233 	struct solo_dev *solo_dev = solo_enc->solo_dev;
234 	u8 interval;
235 
236 	solo_update_mode(solo_enc);
237 
238 	/* Make sure to do a bandwidth check */
239 	if (solo_enc->bw_weight > solo_dev->enc_bw_remain)
240 		return -EBUSY;
241 	solo_enc->sequence = 0;
242 	solo_enc->motion_last_state = false;
243 	solo_enc->frames_since_last_motion = 0;
244 	solo_dev->enc_bw_remain -= solo_enc->bw_weight;
245 
246 	if (solo_enc->type == SOLO_ENC_TYPE_EXT)
247 		solo_reg_write(solo_dev, SOLO_CAP_CH_COMP_ENA_E(ch), 1);
248 
249 	/* Disable all encoding for this channel */
250 	solo_reg_write(solo_dev, SOLO_CAP_CH_SCALE(ch), 0);
251 
252 	/* Common for both std and ext encoding */
253 	solo_reg_write(solo_dev, SOLO_VE_CH_INTL(ch),
254 		       solo_enc->interlaced ? 1 : 0);
255 
256 	if (solo_enc->interlaced)
257 		interval = solo_enc->interval - 1;
258 	else
259 		interval = solo_enc->interval;
260 
261 	/* Standard encoding only */
262 	solo_reg_write(solo_dev, SOLO_VE_CH_GOP(ch), solo_enc->gop);
263 	solo_reg_write(solo_dev, SOLO_VE_CH_QP(ch), solo_enc->qp);
264 	solo_reg_write(solo_dev, SOLO_CAP_CH_INTV(ch), interval);
265 
266 	/* Extended encoding only */
267 	solo_reg_write(solo_dev, SOLO_VE_CH_GOP_E(ch), solo_enc->gop);
268 	solo_reg_write(solo_dev, SOLO_VE_CH_QP_E(ch), solo_enc->qp);
269 	solo_reg_write(solo_dev, SOLO_CAP_CH_INTV_E(ch), interval);
270 
271 	/* Enables the standard encoder */
272 	solo_reg_write(solo_dev, SOLO_CAP_CH_SCALE(ch), solo_enc->mode);
273 
274 	return 0;
275 }
276 
277 static void solo_enc_off(struct solo_enc_dev *solo_enc)
278 {
279 	struct solo_dev *solo_dev = solo_enc->solo_dev;
280 
281 	solo_dev->enc_bw_remain += solo_enc->bw_weight;
282 
283 	solo_reg_write(solo_dev, SOLO_CAP_CH_SCALE(solo_enc->ch), 0);
284 	solo_reg_write(solo_dev, SOLO_CAP_CH_COMP_ENA_E(solo_enc->ch), 0);
285 }
286 
287 static int enc_get_mpeg_dma(struct solo_dev *solo_dev, dma_addr_t dma,
288 			      unsigned int off, unsigned int size)
289 {
290 	int ret;
291 
292 	if (off > SOLO_MP4E_EXT_SIZE(solo_dev))
293 		return -EINVAL;
294 
295 	/* Single shot */
296 	if (off + size <= SOLO_MP4E_EXT_SIZE(solo_dev)) {
297 		return solo_p2m_dma_t(solo_dev, 0, dma,
298 				      SOLO_MP4E_EXT_ADDR(solo_dev) + off, size,
299 				      0, 0);
300 	}
301 
302 	/* Buffer wrap */
303 	ret = solo_p2m_dma_t(solo_dev, 0, dma,
304 			     SOLO_MP4E_EXT_ADDR(solo_dev) + off,
305 			     SOLO_MP4E_EXT_SIZE(solo_dev) - off, 0, 0);
306 
307 	if (!ret) {
308 		ret = solo_p2m_dma_t(solo_dev, 0,
309 			     dma + SOLO_MP4E_EXT_SIZE(solo_dev) - off,
310 			     SOLO_MP4E_EXT_ADDR(solo_dev),
311 			     size + off - SOLO_MP4E_EXT_SIZE(solo_dev), 0, 0);
312 	}
313 
314 	return ret;
315 }
316 
317 /* Build a descriptor queue out of an SG list and send it to the P2M for
318  * processing. */
319 static int solo_send_desc(struct solo_enc_dev *solo_enc, int skip,
320 			  struct sg_table *vbuf, int off, int size,
321 			  unsigned int base, unsigned int base_size)
322 {
323 	struct solo_dev *solo_dev = solo_enc->solo_dev;
324 	struct scatterlist *sg;
325 	int i;
326 	int ret;
327 
328 	if (WARN_ON_ONCE(size > FRAME_BUF_SIZE))
329 		return -EINVAL;
330 
331 	solo_enc->desc_count = 1;
332 
333 	for_each_sg(vbuf->sgl, sg, vbuf->nents, i) {
334 		struct solo_p2m_desc *desc;
335 		dma_addr_t dma;
336 		int len;
337 		int left = base_size - off;
338 
339 		desc = &solo_enc->desc_items[solo_enc->desc_count++];
340 		dma = sg_dma_address(sg);
341 		len = sg_dma_len(sg);
342 
343 		/* We assume this is smaller than the scatter size */
344 		BUG_ON(skip >= len);
345 		if (skip) {
346 			len -= skip;
347 			dma += skip;
348 			size -= skip;
349 			skip = 0;
350 		}
351 
352 		len = min(len, size);
353 
354 		if (len <= left) {
355 			/* Single descriptor */
356 			solo_p2m_fill_desc(desc, 0, dma, base + off,
357 					   len, 0, 0);
358 		} else {
359 			/* Buffer wrap */
360 			/* XXX: Do these as separate DMA requests, to avoid
361 			   timeout errors triggered by awkwardly sized
362 			   descriptors. See
363 			   <https://github.com/bluecherrydvr/solo6x10/issues/8>
364 			 */
365 			ret = solo_p2m_dma_t(solo_dev, 0, dma, base + off,
366 					     left, 0, 0);
367 			if (ret)
368 				return ret;
369 
370 			ret = solo_p2m_dma_t(solo_dev, 0, dma + left, base,
371 					     len - left, 0, 0);
372 			if (ret)
373 				return ret;
374 
375 			solo_enc->desc_count--;
376 		}
377 
378 		size -= len;
379 		if (size <= 0)
380 			break;
381 
382 		off += len;
383 		if (off >= base_size)
384 			off -= base_size;
385 
386 		/* Because we may use two descriptors per loop */
387 		if (solo_enc->desc_count >= (solo_enc->desc_nelts - 1)) {
388 			ret = solo_p2m_dma_desc(solo_dev, solo_enc->desc_items,
389 						solo_enc->desc_dma,
390 						solo_enc->desc_count - 1);
391 			if (ret)
392 				return ret;
393 			solo_enc->desc_count = 1;
394 		}
395 	}
396 
397 	if (solo_enc->desc_count <= 1)
398 		return 0;
399 
400 	return solo_p2m_dma_desc(solo_dev, solo_enc->desc_items,
401 			solo_enc->desc_dma, solo_enc->desc_count - 1);
402 }
403 
404 /* Extract values from VOP header - VE_STATUSxx */
405 static inline int vop_interlaced(const vop_header *vh)
406 {
407 	return (__le32_to_cpu((*vh)[0]) >> 30) & 1;
408 }
409 
410 static inline u8 vop_channel(const vop_header *vh)
411 {
412 	return (__le32_to_cpu((*vh)[0]) >> 24) & 0x1F;
413 }
414 
415 static inline u8 vop_type(const vop_header *vh)
416 {
417 	return (__le32_to_cpu((*vh)[0]) >> 22) & 3;
418 }
419 
420 static inline u32 vop_mpeg_size(const vop_header *vh)
421 {
422 	return __le32_to_cpu((*vh)[0]) & 0xFFFFF;
423 }
424 
425 static inline u8 vop_hsize(const vop_header *vh)
426 {
427 	return (__le32_to_cpu((*vh)[1]) >> 8) & 0xFF;
428 }
429 
430 static inline u8 vop_vsize(const vop_header *vh)
431 {
432 	return __le32_to_cpu((*vh)[1]) & 0xFF;
433 }
434 
435 static inline u32 vop_mpeg_offset(const vop_header *vh)
436 {
437 	return __le32_to_cpu((*vh)[2]);
438 }
439 
440 static inline u32 vop_jpeg_offset(const vop_header *vh)
441 {
442 	return __le32_to_cpu((*vh)[3]);
443 }
444 
445 static inline u32 vop_jpeg_size(const vop_header *vh)
446 {
447 	return __le32_to_cpu((*vh)[4]) & 0xFFFFF;
448 }
449 
450 static inline u32 vop_sec(const vop_header *vh)
451 {
452 	return __le32_to_cpu((*vh)[5]);
453 }
454 
455 static inline u32 vop_usec(const vop_header *vh)
456 {
457 	return __le32_to_cpu((*vh)[6]);
458 }
459 
460 static int solo_fill_jpeg(struct solo_enc_dev *solo_enc,
461 			  struct vb2_buffer *vb, const vop_header *vh)
462 {
463 	struct solo_dev *solo_dev = solo_enc->solo_dev;
464 	struct sg_table *vbuf = vb2_dma_sg_plane_desc(vb, 0);
465 	int frame_size;
466 
467 	vb->v4l2_buf.flags |= V4L2_BUF_FLAG_KEYFRAME;
468 
469 	if (vb2_plane_size(vb, 0) < vop_jpeg_size(vh) + solo_enc->jpeg_len)
470 		return -EIO;
471 
472 	frame_size = ALIGN(vop_jpeg_size(vh) + solo_enc->jpeg_len, DMA_ALIGN);
473 	vb2_set_plane_payload(vb, 0, vop_jpeg_size(vh) + solo_enc->jpeg_len);
474 
475 	return solo_send_desc(solo_enc, solo_enc->jpeg_len, vbuf,
476 			     vop_jpeg_offset(vh) - SOLO_JPEG_EXT_ADDR(solo_dev),
477 			     frame_size, SOLO_JPEG_EXT_ADDR(solo_dev),
478 			     SOLO_JPEG_EXT_SIZE(solo_dev));
479 }
480 
481 static int solo_fill_mpeg(struct solo_enc_dev *solo_enc,
482 		struct vb2_buffer *vb, const vop_header *vh)
483 {
484 	struct solo_dev *solo_dev = solo_enc->solo_dev;
485 	struct sg_table *vbuf = vb2_dma_sg_plane_desc(vb, 0);
486 	int frame_off, frame_size;
487 	int skip = 0;
488 
489 	if (vb2_plane_size(vb, 0) < vop_mpeg_size(vh))
490 		return -EIO;
491 
492 	/* If this is a key frame, add extra header */
493 	vb->v4l2_buf.flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME |
494 		V4L2_BUF_FLAG_BFRAME);
495 	if (!vop_type(vh)) {
496 		skip = solo_enc->vop_len;
497 		vb->v4l2_buf.flags |= V4L2_BUF_FLAG_KEYFRAME;
498 		vb2_set_plane_payload(vb, 0, vop_mpeg_size(vh) +
499 			solo_enc->vop_len);
500 	} else {
501 		vb->v4l2_buf.flags |= V4L2_BUF_FLAG_PFRAME;
502 		vb2_set_plane_payload(vb, 0, vop_mpeg_size(vh));
503 	}
504 
505 	/* Now get the actual mpeg payload */
506 	frame_off = (vop_mpeg_offset(vh) - SOLO_MP4E_EXT_ADDR(solo_dev) +
507 		sizeof(*vh)) % SOLO_MP4E_EXT_SIZE(solo_dev);
508 	frame_size = ALIGN(vop_mpeg_size(vh) + skip, DMA_ALIGN);
509 
510 	return solo_send_desc(solo_enc, skip, vbuf, frame_off, frame_size,
511 			SOLO_MP4E_EXT_ADDR(solo_dev),
512 			SOLO_MP4E_EXT_SIZE(solo_dev));
513 }
514 
515 static int solo_enc_fillbuf(struct solo_enc_dev *solo_enc,
516 			    struct vb2_buffer *vb, struct solo_enc_buf *enc_buf)
517 {
518 	const vop_header *vh = enc_buf->vh;
519 	int ret;
520 
521 	switch (solo_enc->fmt) {
522 	case V4L2_PIX_FMT_MPEG4:
523 	case V4L2_PIX_FMT_H264:
524 		ret = solo_fill_mpeg(solo_enc, vb, vh);
525 		break;
526 	default: /* V4L2_PIX_FMT_MJPEG */
527 		ret = solo_fill_jpeg(solo_enc, vb, vh);
528 		break;
529 	}
530 
531 	if (!ret) {
532 		bool send_event = false;
533 
534 		vb->v4l2_buf.sequence = solo_enc->sequence++;
535 		vb->v4l2_buf.timestamp.tv_sec = vop_sec(vh);
536 		vb->v4l2_buf.timestamp.tv_usec = vop_usec(vh);
537 
538 		/* Check for motion flags */
539 		if (solo_is_motion_on(solo_enc)) {
540 			/* It takes a few frames for the hardware to detect
541 			 * motion. Once it does it clears the motion detection
542 			 * register and it takes again a few frames before
543 			 * motion is seen. This means in practice that when the
544 			 * motion field is 1, it will go back to 0 for the next
545 			 * frame. This leads to motion detection event being
546 			 * sent all the time, which is not what we want.
547 			 * Instead wait a few frames before deciding that the
548 			 * motion has halted. After some experimentation it
549 			 * turns out that waiting for 5 frames works well.
550 			 */
551 			if (enc_buf->motion == 0 &&
552 			    solo_enc->motion_last_state &&
553 			    solo_enc->frames_since_last_motion++ > 5)
554 				send_event = true;
555 			else if (enc_buf->motion) {
556 				solo_enc->frames_since_last_motion = 0;
557 				send_event = !solo_enc->motion_last_state;
558 			}
559 		}
560 
561 		if (send_event) {
562 			struct v4l2_event ev = {
563 				.type = V4L2_EVENT_MOTION_DET,
564 				.u.motion_det = {
565 					.flags = V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ,
566 					.frame_sequence = vb->v4l2_buf.sequence,
567 					.region_mask = enc_buf->motion ? 1 : 0,
568 				},
569 			};
570 
571 			solo_enc->motion_last_state = enc_buf->motion;
572 			solo_enc->frames_since_last_motion = 0;
573 			v4l2_event_queue(solo_enc->vfd, &ev);
574 		}
575 	}
576 
577 	vb2_buffer_done(vb, ret ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
578 
579 	return ret;
580 }
581 
582 static void solo_enc_handle_one(struct solo_enc_dev *solo_enc,
583 				struct solo_enc_buf *enc_buf)
584 {
585 	struct solo_vb2_buf *vb;
586 	unsigned long flags;
587 
588 	mutex_lock(&solo_enc->lock);
589 	if (solo_enc->type != enc_buf->type)
590 		goto unlock;
591 
592 	spin_lock_irqsave(&solo_enc->av_lock, flags);
593 	if (list_empty(&solo_enc->vidq_active)) {
594 		spin_unlock_irqrestore(&solo_enc->av_lock, flags);
595 		goto unlock;
596 	}
597 	vb = list_first_entry(&solo_enc->vidq_active, struct solo_vb2_buf,
598 		list);
599 	list_del(&vb->list);
600 	spin_unlock_irqrestore(&solo_enc->av_lock, flags);
601 
602 	solo_enc_fillbuf(solo_enc, &vb->vb, enc_buf);
603 unlock:
604 	mutex_unlock(&solo_enc->lock);
605 }
606 
607 void solo_enc_v4l2_isr(struct solo_dev *solo_dev)
608 {
609 	wake_up_interruptible_all(&solo_dev->ring_thread_wait);
610 }
611 
612 static void solo_handle_ring(struct solo_dev *solo_dev)
613 {
614 	for (;;) {
615 		struct solo_enc_dev *solo_enc;
616 		struct solo_enc_buf enc_buf;
617 		u32 mpeg_current, off;
618 		u8 ch;
619 		u8 cur_q;
620 
621 		/* Check if the hardware has any new ones in the queue */
622 		cur_q = solo_reg_read(solo_dev, SOLO_VE_STATE(11)) & 0xff;
623 		if (cur_q == solo_dev->enc_idx)
624 			break;
625 
626 		mpeg_current = solo_reg_read(solo_dev,
627 					SOLO_VE_MPEG4_QUE(solo_dev->enc_idx));
628 		solo_dev->enc_idx = (solo_dev->enc_idx + 1) % MP4_QS;
629 
630 		ch = (mpeg_current >> 24) & 0x1f;
631 		off = mpeg_current & 0x00ffffff;
632 
633 		if (ch >= SOLO_MAX_CHANNELS) {
634 			ch -= SOLO_MAX_CHANNELS;
635 			enc_buf.type = SOLO_ENC_TYPE_EXT;
636 		} else
637 			enc_buf.type = SOLO_ENC_TYPE_STD;
638 
639 		solo_enc = solo_dev->v4l2_enc[ch];
640 		if (solo_enc == NULL) {
641 			dev_err(&solo_dev->pdev->dev,
642 				"Got spurious packet for channel %d\n", ch);
643 			continue;
644 		}
645 
646 		/* FAIL... */
647 		if (enc_get_mpeg_dma(solo_dev, solo_dev->vh_dma, off,
648 				     sizeof(vop_header)))
649 			continue;
650 
651 		enc_buf.vh = solo_dev->vh_buf;
652 
653 		/* Sanity check */
654 		if (vop_mpeg_offset(enc_buf.vh) !=
655 			SOLO_MP4E_EXT_ADDR(solo_dev) + off)
656 			continue;
657 
658 		if (solo_motion_detected(solo_enc))
659 			enc_buf.motion = 1;
660 		else
661 			enc_buf.motion = 0;
662 
663 		solo_enc_handle_one(solo_enc, &enc_buf);
664 	}
665 }
666 
667 static int solo_ring_thread(void *data)
668 {
669 	struct solo_dev *solo_dev = data;
670 	DECLARE_WAITQUEUE(wait, current);
671 
672 	set_freezable();
673 	add_wait_queue(&solo_dev->ring_thread_wait, &wait);
674 
675 	for (;;) {
676 		long timeout = schedule_timeout_interruptible(HZ);
677 
678 		if (timeout == -ERESTARTSYS || kthread_should_stop())
679 			break;
680 		solo_handle_ring(solo_dev);
681 		try_to_freeze();
682 	}
683 
684 	remove_wait_queue(&solo_dev->ring_thread_wait, &wait);
685 
686 	return 0;
687 }
688 
689 static int solo_enc_queue_setup(struct vb2_queue *q,
690 				const struct v4l2_format *fmt,
691 				unsigned int *num_buffers,
692 				unsigned int *num_planes, unsigned int sizes[],
693 				void *alloc_ctxs[])
694 {
695 	struct solo_enc_dev *solo_enc = vb2_get_drv_priv(q);
696 
697 	sizes[0] = FRAME_BUF_SIZE;
698 	alloc_ctxs[0] = solo_enc->alloc_ctx;
699 	*num_planes = 1;
700 
701 	if (*num_buffers < MIN_VID_BUFFERS)
702 		*num_buffers = MIN_VID_BUFFERS;
703 
704 	return 0;
705 }
706 
707 static void solo_enc_buf_queue(struct vb2_buffer *vb)
708 {
709 	struct vb2_queue *vq = vb->vb2_queue;
710 	struct solo_enc_dev *solo_enc = vb2_get_drv_priv(vq);
711 	struct solo_vb2_buf *solo_vb =
712 		container_of(vb, struct solo_vb2_buf, vb);
713 
714 	spin_lock(&solo_enc->av_lock);
715 	list_add_tail(&solo_vb->list, &solo_enc->vidq_active);
716 	spin_unlock(&solo_enc->av_lock);
717 }
718 
719 static int solo_ring_start(struct solo_dev *solo_dev)
720 {
721 	solo_dev->ring_thread = kthread_run(solo_ring_thread, solo_dev,
722 					    SOLO6X10_NAME "_ring");
723 	if (IS_ERR(solo_dev->ring_thread)) {
724 		int err = PTR_ERR(solo_dev->ring_thread);
725 
726 		solo_dev->ring_thread = NULL;
727 		return err;
728 	}
729 
730 	solo_irq_on(solo_dev, SOLO_IRQ_ENCODER);
731 
732 	return 0;
733 }
734 
735 static void solo_ring_stop(struct solo_dev *solo_dev)
736 {
737 	if (solo_dev->ring_thread) {
738 		kthread_stop(solo_dev->ring_thread);
739 		solo_dev->ring_thread = NULL;
740 	}
741 
742 	solo_irq_off(solo_dev, SOLO_IRQ_ENCODER);
743 }
744 
745 static int solo_enc_start_streaming(struct vb2_queue *q, unsigned int count)
746 {
747 	struct solo_enc_dev *solo_enc = vb2_get_drv_priv(q);
748 
749 	return solo_enc_on(solo_enc);
750 }
751 
752 static void solo_enc_stop_streaming(struct vb2_queue *q)
753 {
754 	struct solo_enc_dev *solo_enc = vb2_get_drv_priv(q);
755 	unsigned long flags;
756 
757 	spin_lock_irqsave(&solo_enc->av_lock, flags);
758 	solo_enc_off(solo_enc);
759 	while (!list_empty(&solo_enc->vidq_active)) {
760 		struct solo_vb2_buf *buf = list_entry(
761 				solo_enc->vidq_active.next,
762 				struct solo_vb2_buf, list);
763 
764 		list_del(&buf->list);
765 		vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
766 	}
767 	spin_unlock_irqrestore(&solo_enc->av_lock, flags);
768 }
769 
770 static void solo_enc_buf_finish(struct vb2_buffer *vb)
771 {
772 	struct solo_enc_dev *solo_enc = vb2_get_drv_priv(vb->vb2_queue);
773 	struct sg_table *vbuf = vb2_dma_sg_plane_desc(vb, 0);
774 
775 	switch (solo_enc->fmt) {
776 	case V4L2_PIX_FMT_MPEG4:
777 	case V4L2_PIX_FMT_H264:
778 		if (vb->v4l2_buf.flags & V4L2_BUF_FLAG_KEYFRAME)
779 			sg_copy_from_buffer(vbuf->sgl, vbuf->nents,
780 					solo_enc->vop, solo_enc->vop_len);
781 		break;
782 	default: /* V4L2_PIX_FMT_MJPEG */
783 		sg_copy_from_buffer(vbuf->sgl, vbuf->nents,
784 				solo_enc->jpeg_header, solo_enc->jpeg_len);
785 		break;
786 	}
787 }
788 
789 static struct vb2_ops solo_enc_video_qops = {
790 	.queue_setup	= solo_enc_queue_setup,
791 	.buf_queue	= solo_enc_buf_queue,
792 	.buf_finish	= solo_enc_buf_finish,
793 	.start_streaming = solo_enc_start_streaming,
794 	.stop_streaming = solo_enc_stop_streaming,
795 	.wait_prepare	= vb2_ops_wait_prepare,
796 	.wait_finish	= vb2_ops_wait_finish,
797 };
798 
799 static int solo_enc_querycap(struct file *file, void  *priv,
800 			     struct v4l2_capability *cap)
801 {
802 	struct solo_enc_dev *solo_enc = video_drvdata(file);
803 	struct solo_dev *solo_dev = solo_enc->solo_dev;
804 
805 	strcpy(cap->driver, SOLO6X10_NAME);
806 	snprintf(cap->card, sizeof(cap->card), "Softlogic 6x10 Enc %d",
807 		 solo_enc->ch);
808 	snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s",
809 		 pci_name(solo_dev->pdev));
810 	cap->device_caps = V4L2_CAP_VIDEO_CAPTURE |
811 			V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
812 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
813 	return 0;
814 }
815 
816 static int solo_enc_enum_input(struct file *file, void *priv,
817 			       struct v4l2_input *input)
818 {
819 	struct solo_enc_dev *solo_enc = video_drvdata(file);
820 	struct solo_dev *solo_dev = solo_enc->solo_dev;
821 
822 	if (input->index)
823 		return -EINVAL;
824 
825 	snprintf(input->name, sizeof(input->name), "Encoder %d",
826 		 solo_enc->ch + 1);
827 	input->type = V4L2_INPUT_TYPE_CAMERA;
828 	input->std = solo_enc->vfd->tvnorms;
829 
830 	if (!tw28_get_video_status(solo_dev, solo_enc->ch))
831 		input->status = V4L2_IN_ST_NO_SIGNAL;
832 
833 	return 0;
834 }
835 
836 static int solo_enc_set_input(struct file *file, void *priv,
837 			      unsigned int index)
838 {
839 	if (index)
840 		return -EINVAL;
841 
842 	return 0;
843 }
844 
845 static int solo_enc_get_input(struct file *file, void *priv,
846 			      unsigned int *index)
847 {
848 	*index = 0;
849 
850 	return 0;
851 }
852 
853 static int solo_enc_enum_fmt_cap(struct file *file, void *priv,
854 				 struct v4l2_fmtdesc *f)
855 {
856 	struct solo_enc_dev *solo_enc = video_drvdata(file);
857 	int dev_type = solo_enc->solo_dev->type;
858 
859 	switch (f->index) {
860 	case 0:
861 		switch (dev_type) {
862 		case SOLO_DEV_6010:
863 			f->pixelformat = V4L2_PIX_FMT_MPEG4;
864 			strcpy(f->description, "MPEG-4 part 2");
865 			break;
866 		case SOLO_DEV_6110:
867 			f->pixelformat = V4L2_PIX_FMT_H264;
868 			strcpy(f->description, "H.264");
869 			break;
870 		}
871 		break;
872 	case 1:
873 		f->pixelformat = V4L2_PIX_FMT_MJPEG;
874 		strcpy(f->description, "MJPEG");
875 		break;
876 	default:
877 		return -EINVAL;
878 	}
879 
880 	f->flags = V4L2_FMT_FLAG_COMPRESSED;
881 
882 	return 0;
883 }
884 
885 static inline int solo_valid_pixfmt(u32 pixfmt, int dev_type)
886 {
887 	return (pixfmt == V4L2_PIX_FMT_H264 && dev_type == SOLO_DEV_6110)
888 		|| (pixfmt == V4L2_PIX_FMT_MPEG4 && dev_type == SOLO_DEV_6010)
889 		|| pixfmt == V4L2_PIX_FMT_MJPEG ? 0 : -EINVAL;
890 }
891 
892 static int solo_enc_try_fmt_cap(struct file *file, void *priv,
893 			    struct v4l2_format *f)
894 {
895 	struct solo_enc_dev *solo_enc = video_drvdata(file);
896 	struct solo_dev *solo_dev = solo_enc->solo_dev;
897 	struct v4l2_pix_format *pix = &f->fmt.pix;
898 
899 	if (solo_valid_pixfmt(pix->pixelformat, solo_dev->type))
900 		return -EINVAL;
901 
902 	if (pix->width < solo_dev->video_hsize ||
903 	    pix->height < solo_dev->video_vsize << 1) {
904 		/* Default to CIF 1/2 size */
905 		pix->width = solo_dev->video_hsize >> 1;
906 		pix->height = solo_dev->video_vsize;
907 	} else {
908 		/* Full frame */
909 		pix->width = solo_dev->video_hsize;
910 		pix->height = solo_dev->video_vsize << 1;
911 	}
912 
913 	switch (pix->field) {
914 	case V4L2_FIELD_NONE:
915 	case V4L2_FIELD_INTERLACED:
916 		break;
917 	case V4L2_FIELD_ANY:
918 	default:
919 		pix->field = V4L2_FIELD_INTERLACED;
920 		break;
921 	}
922 
923 	/* Just set these */
924 	pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
925 	pix->sizeimage = FRAME_BUF_SIZE;
926 	pix->bytesperline = 0;
927 	pix->priv = 0;
928 
929 	return 0;
930 }
931 
932 static int solo_enc_set_fmt_cap(struct file *file, void *priv,
933 				struct v4l2_format *f)
934 {
935 	struct solo_enc_dev *solo_enc = video_drvdata(file);
936 	struct solo_dev *solo_dev = solo_enc->solo_dev;
937 	struct v4l2_pix_format *pix = &f->fmt.pix;
938 	int ret;
939 
940 	if (vb2_is_busy(&solo_enc->vidq))
941 		return -EBUSY;
942 
943 	ret = solo_enc_try_fmt_cap(file, priv, f);
944 	if (ret)
945 		return ret;
946 
947 	if (pix->width == solo_dev->video_hsize)
948 		solo_enc->mode = SOLO_ENC_MODE_D1;
949 	else
950 		solo_enc->mode = SOLO_ENC_MODE_CIF;
951 
952 	/* This does not change the encoder at all */
953 	solo_enc->fmt = pix->pixelformat;
954 
955 	/*
956 	 * More information is needed about these 'extended' types. As far
957 	 * as I can tell these are basically additional video streams with
958 	 * different MPEG encoding attributes that can run in parallel with
959 	 * the main stream. If so, then this should be implemented as a
960 	 * second video node. Abusing priv like this is certainly not the
961 	 * right approach.
962 	if (pix->priv)
963 		solo_enc->type = SOLO_ENC_TYPE_EXT;
964 	 */
965 	solo_update_mode(solo_enc);
966 	return 0;
967 }
968 
969 static int solo_enc_get_fmt_cap(struct file *file, void *priv,
970 				struct v4l2_format *f)
971 {
972 	struct solo_enc_dev *solo_enc = video_drvdata(file);
973 	struct v4l2_pix_format *pix = &f->fmt.pix;
974 
975 	pix->width = solo_enc->width;
976 	pix->height = solo_enc->height;
977 	pix->pixelformat = solo_enc->fmt;
978 	pix->field = solo_enc->interlaced ? V4L2_FIELD_INTERLACED :
979 		     V4L2_FIELD_NONE;
980 	pix->sizeimage = FRAME_BUF_SIZE;
981 	pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
982 	pix->priv = 0;
983 
984 	return 0;
985 }
986 
987 static int solo_enc_g_std(struct file *file, void *priv, v4l2_std_id *i)
988 {
989 	struct solo_enc_dev *solo_enc = video_drvdata(file);
990 	struct solo_dev *solo_dev = solo_enc->solo_dev;
991 
992 	if (solo_dev->video_type == SOLO_VO_FMT_TYPE_NTSC)
993 		*i = V4L2_STD_NTSC_M;
994 	else
995 		*i = V4L2_STD_PAL;
996 	return 0;
997 }
998 
999 static int solo_enc_s_std(struct file *file, void *priv, v4l2_std_id std)
1000 {
1001 	struct solo_enc_dev *solo_enc = video_drvdata(file);
1002 
1003 	return solo_set_video_type(solo_enc->solo_dev, std & V4L2_STD_625_50);
1004 }
1005 
1006 static int solo_enum_framesizes(struct file *file, void *priv,
1007 				struct v4l2_frmsizeenum *fsize)
1008 {
1009 	struct solo_enc_dev *solo_enc = video_drvdata(file);
1010 	struct solo_dev *solo_dev = solo_enc->solo_dev;
1011 
1012 	if (solo_valid_pixfmt(fsize->pixel_format, solo_dev->type))
1013 		return -EINVAL;
1014 
1015 	switch (fsize->index) {
1016 	case 0:
1017 		fsize->discrete.width = solo_dev->video_hsize >> 1;
1018 		fsize->discrete.height = solo_dev->video_vsize;
1019 		break;
1020 	case 1:
1021 		fsize->discrete.width = solo_dev->video_hsize;
1022 		fsize->discrete.height = solo_dev->video_vsize << 1;
1023 		break;
1024 	default:
1025 		return -EINVAL;
1026 	}
1027 
1028 	fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1029 
1030 	return 0;
1031 }
1032 
1033 static int solo_enum_frameintervals(struct file *file, void *priv,
1034 				    struct v4l2_frmivalenum *fintv)
1035 {
1036 	struct solo_enc_dev *solo_enc = video_drvdata(file);
1037 	struct solo_dev *solo_dev = solo_enc->solo_dev;
1038 
1039 	if (solo_valid_pixfmt(fintv->pixel_format, solo_dev->type))
1040 		return -EINVAL;
1041 	if (fintv->index)
1042 		return -EINVAL;
1043 	if ((fintv->width != solo_dev->video_hsize >> 1 ||
1044 	     fintv->height != solo_dev->video_vsize) &&
1045 	    (fintv->width != solo_dev->video_hsize ||
1046 	     fintv->height != solo_dev->video_vsize << 1))
1047 		return -EINVAL;
1048 
1049 	fintv->type = V4L2_FRMIVAL_TYPE_STEPWISE;
1050 
1051 	fintv->stepwise.min.numerator = 1;
1052 	fintv->stepwise.min.denominator = solo_dev->fps;
1053 
1054 	fintv->stepwise.max.numerator = 15;
1055 	fintv->stepwise.max.denominator = solo_dev->fps;
1056 
1057 	fintv->stepwise.step.numerator = 1;
1058 	fintv->stepwise.step.denominator = solo_dev->fps;
1059 
1060 	return 0;
1061 }
1062 
1063 static int solo_g_parm(struct file *file, void *priv,
1064 		       struct v4l2_streamparm *sp)
1065 {
1066 	struct solo_enc_dev *solo_enc = video_drvdata(file);
1067 	struct v4l2_captureparm *cp = &sp->parm.capture;
1068 
1069 	cp->capability = V4L2_CAP_TIMEPERFRAME;
1070 	cp->timeperframe.numerator = solo_enc->interval;
1071 	cp->timeperframe.denominator = solo_enc->solo_dev->fps;
1072 	cp->capturemode = 0;
1073 	/* XXX: Shouldn't we be able to get/set this from videobuf? */
1074 	cp->readbuffers = 2;
1075 
1076 	return 0;
1077 }
1078 
1079 static inline int calc_interval(u8 fps, u32 n, u32 d)
1080 {
1081 	if (!n || !d)
1082 		return 1;
1083 	if (d == fps)
1084 		return n;
1085 	n *= fps;
1086 	return min(15U, n / d + (n % d >= (fps >> 1)));
1087 }
1088 
1089 static int solo_s_parm(struct file *file, void *priv,
1090 		       struct v4l2_streamparm *sp)
1091 {
1092 	struct solo_enc_dev *solo_enc = video_drvdata(file);
1093 	struct v4l2_fract *t = &sp->parm.capture.timeperframe;
1094 	u8 fps = solo_enc->solo_dev->fps;
1095 
1096 	if (vb2_is_streaming(&solo_enc->vidq))
1097 		return -EBUSY;
1098 
1099 	solo_enc->interval = calc_interval(fps, t->numerator, t->denominator);
1100 	solo_update_mode(solo_enc);
1101 	return solo_g_parm(file, priv, sp);
1102 }
1103 
1104 static int solo_s_ctrl(struct v4l2_ctrl *ctrl)
1105 {
1106 	struct solo_enc_dev *solo_enc =
1107 		container_of(ctrl->handler, struct solo_enc_dev, hdl);
1108 	struct solo_dev *solo_dev = solo_enc->solo_dev;
1109 	int err;
1110 
1111 	switch (ctrl->id) {
1112 	case V4L2_CID_BRIGHTNESS:
1113 	case V4L2_CID_CONTRAST:
1114 	case V4L2_CID_SATURATION:
1115 	case V4L2_CID_HUE:
1116 	case V4L2_CID_SHARPNESS:
1117 		return tw28_set_ctrl_val(solo_dev, ctrl->id, solo_enc->ch,
1118 					 ctrl->val);
1119 	case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
1120 		solo_enc->gop = ctrl->val;
1121 		solo_reg_write(solo_dev, SOLO_VE_CH_GOP(solo_enc->ch), solo_enc->gop);
1122 		solo_reg_write(solo_dev, SOLO_VE_CH_GOP_E(solo_enc->ch), solo_enc->gop);
1123 		return 0;
1124 	case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
1125 		solo_enc->qp = ctrl->val;
1126 		solo_reg_write(solo_dev, SOLO_VE_CH_QP(solo_enc->ch), solo_enc->qp);
1127 		solo_reg_write(solo_dev, SOLO_VE_CH_QP_E(solo_enc->ch), solo_enc->qp);
1128 		return 0;
1129 	case V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD:
1130 		solo_enc->motion_thresh = ctrl->val << 8;
1131 		if (!solo_enc->motion_global || !solo_enc->motion_enabled)
1132 			return 0;
1133 		return solo_set_motion_threshold(solo_dev, solo_enc->ch,
1134 				solo_enc->motion_thresh);
1135 	case V4L2_CID_DETECT_MD_MODE:
1136 		solo_enc->motion_global = ctrl->val == V4L2_DETECT_MD_MODE_GLOBAL;
1137 		solo_enc->motion_enabled = ctrl->val > V4L2_DETECT_MD_MODE_DISABLED;
1138 		if (ctrl->val) {
1139 			if (solo_enc->motion_global)
1140 				err = solo_set_motion_threshold(solo_dev, solo_enc->ch,
1141 					solo_enc->motion_thresh);
1142 			else
1143 				err = solo_set_motion_block(solo_dev, solo_enc->ch,
1144 					solo_enc->md_thresholds->p_cur.p_u16);
1145 			if (err)
1146 				return err;
1147 		}
1148 		solo_motion_toggle(solo_enc, ctrl->val);
1149 		return 0;
1150 	case V4L2_CID_DETECT_MD_THRESHOLD_GRID:
1151 		if (solo_enc->motion_enabled && !solo_enc->motion_global)
1152 			return solo_set_motion_block(solo_dev, solo_enc->ch,
1153 					solo_enc->md_thresholds->p_new.p_u16);
1154 		break;
1155 	case V4L2_CID_OSD_TEXT:
1156 		strcpy(solo_enc->osd_text, ctrl->p_new.p_char);
1157 		return solo_osd_print(solo_enc);
1158 	default:
1159 		return -EINVAL;
1160 	}
1161 
1162 	return 0;
1163 }
1164 
1165 static int solo_subscribe_event(struct v4l2_fh *fh,
1166 				const struct v4l2_event_subscription *sub)
1167 {
1168 
1169 	switch (sub->type) {
1170 	case V4L2_EVENT_CTRL:
1171 		return v4l2_ctrl_subscribe_event(fh, sub);
1172 	case V4L2_EVENT_MOTION_DET:
1173 		/* Allow for up to 30 events (1 second for NTSC) to be
1174 		 * stored. */
1175 		return v4l2_event_subscribe(fh, sub, 30, NULL);
1176 	}
1177 	return -EINVAL;
1178 }
1179 
1180 static const struct v4l2_file_operations solo_enc_fops = {
1181 	.owner			= THIS_MODULE,
1182 	.open			= v4l2_fh_open,
1183 	.release		= vb2_fop_release,
1184 	.read			= vb2_fop_read,
1185 	.poll			= vb2_fop_poll,
1186 	.mmap			= vb2_fop_mmap,
1187 	.unlocked_ioctl		= video_ioctl2,
1188 };
1189 
1190 static const struct v4l2_ioctl_ops solo_enc_ioctl_ops = {
1191 	.vidioc_querycap		= solo_enc_querycap,
1192 	.vidioc_s_std			= solo_enc_s_std,
1193 	.vidioc_g_std			= solo_enc_g_std,
1194 	/* Input callbacks */
1195 	.vidioc_enum_input		= solo_enc_enum_input,
1196 	.vidioc_s_input			= solo_enc_set_input,
1197 	.vidioc_g_input			= solo_enc_get_input,
1198 	/* Video capture format callbacks */
1199 	.vidioc_enum_fmt_vid_cap	= solo_enc_enum_fmt_cap,
1200 	.vidioc_try_fmt_vid_cap		= solo_enc_try_fmt_cap,
1201 	.vidioc_s_fmt_vid_cap		= solo_enc_set_fmt_cap,
1202 	.vidioc_g_fmt_vid_cap		= solo_enc_get_fmt_cap,
1203 	/* Streaming I/O */
1204 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
1205 	.vidioc_querybuf		= vb2_ioctl_querybuf,
1206 	.vidioc_qbuf			= vb2_ioctl_qbuf,
1207 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
1208 	.vidioc_streamon		= vb2_ioctl_streamon,
1209 	.vidioc_streamoff		= vb2_ioctl_streamoff,
1210 	/* Frame size and interval */
1211 	.vidioc_enum_framesizes		= solo_enum_framesizes,
1212 	.vidioc_enum_frameintervals	= solo_enum_frameintervals,
1213 	/* Video capture parameters */
1214 	.vidioc_s_parm			= solo_s_parm,
1215 	.vidioc_g_parm			= solo_g_parm,
1216 	/* Logging and events */
1217 	.vidioc_log_status		= v4l2_ctrl_log_status,
1218 	.vidioc_subscribe_event		= solo_subscribe_event,
1219 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
1220 };
1221 
1222 static const struct video_device solo_enc_template = {
1223 	.name			= SOLO6X10_NAME,
1224 	.fops			= &solo_enc_fops,
1225 	.ioctl_ops		= &solo_enc_ioctl_ops,
1226 	.minor			= -1,
1227 	.release		= video_device_release,
1228 	.tvnorms		= V4L2_STD_NTSC_M | V4L2_STD_PAL,
1229 };
1230 
1231 static const struct v4l2_ctrl_ops solo_ctrl_ops = {
1232 	.s_ctrl = solo_s_ctrl,
1233 };
1234 
1235 static const struct v4l2_ctrl_config solo_osd_text_ctrl = {
1236 	.ops = &solo_ctrl_ops,
1237 	.id = V4L2_CID_OSD_TEXT,
1238 	.name = "OSD Text",
1239 	.type = V4L2_CTRL_TYPE_STRING,
1240 	.max = OSD_TEXT_MAX,
1241 	.step = 1,
1242 };
1243 
1244 /* Motion Detection Threshold matrix */
1245 static const struct v4l2_ctrl_config solo_md_thresholds = {
1246 	.ops = &solo_ctrl_ops,
1247 	.id = V4L2_CID_DETECT_MD_THRESHOLD_GRID,
1248 	.dims = { SOLO_MOTION_SZ, SOLO_MOTION_SZ },
1249 	.def = SOLO_DEF_MOT_THRESH,
1250 	.max = 65535,
1251 	.step = 1,
1252 };
1253 
1254 static struct solo_enc_dev *solo_enc_alloc(struct solo_dev *solo_dev,
1255 					   u8 ch, unsigned nr)
1256 {
1257 	struct solo_enc_dev *solo_enc;
1258 	struct v4l2_ctrl_handler *hdl;
1259 	int ret;
1260 
1261 	solo_enc = kzalloc(sizeof(*solo_enc), GFP_KERNEL);
1262 	if (!solo_enc)
1263 		return ERR_PTR(-ENOMEM);
1264 
1265 	hdl = &solo_enc->hdl;
1266 	solo_enc->alloc_ctx = vb2_dma_sg_init_ctx(&solo_dev->pdev->dev);
1267 	if (IS_ERR(solo_enc->alloc_ctx)) {
1268 		ret = PTR_ERR(solo_enc->alloc_ctx);
1269 		goto hdl_free;
1270 	}
1271 	v4l2_ctrl_handler_init(hdl, 10);
1272 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1273 			V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
1274 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1275 			V4L2_CID_CONTRAST, 0, 255, 1, 128);
1276 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1277 			V4L2_CID_SATURATION, 0, 255, 1, 128);
1278 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1279 			V4L2_CID_HUE, 0, 255, 1, 128);
1280 	if (tw28_has_sharpness(solo_dev, ch))
1281 		v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1282 			V4L2_CID_SHARPNESS, 0, 15, 1, 0);
1283 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1284 			V4L2_CID_MPEG_VIDEO_GOP_SIZE, 1, 255, 1, solo_dev->fps);
1285 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1286 			V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 31, 1, SOLO_DEFAULT_QP);
1287 	v4l2_ctrl_new_std_menu(hdl, &solo_ctrl_ops,
1288 			V4L2_CID_DETECT_MD_MODE,
1289 			V4L2_DETECT_MD_MODE_THRESHOLD_GRID, 0,
1290 			V4L2_DETECT_MD_MODE_DISABLED);
1291 	v4l2_ctrl_new_std(hdl, &solo_ctrl_ops,
1292 			V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD, 0, 0xff, 1,
1293 			SOLO_DEF_MOT_THRESH >> 8);
1294 	v4l2_ctrl_new_custom(hdl, &solo_osd_text_ctrl, NULL);
1295 	solo_enc->md_thresholds =
1296 		v4l2_ctrl_new_custom(hdl, &solo_md_thresholds, NULL);
1297 	if (hdl->error) {
1298 		ret = hdl->error;
1299 		goto hdl_free;
1300 	}
1301 
1302 	solo_enc->solo_dev = solo_dev;
1303 	solo_enc->ch = ch;
1304 	mutex_init(&solo_enc->lock);
1305 	spin_lock_init(&solo_enc->av_lock);
1306 	INIT_LIST_HEAD(&solo_enc->vidq_active);
1307 	solo_enc->fmt = (solo_dev->type == SOLO_DEV_6010) ?
1308 		V4L2_PIX_FMT_MPEG4 : V4L2_PIX_FMT_H264;
1309 	solo_enc->type = SOLO_ENC_TYPE_STD;
1310 
1311 	solo_enc->qp = SOLO_DEFAULT_QP;
1312 	solo_enc->gop = solo_dev->fps;
1313 	solo_enc->interval = 1;
1314 	solo_enc->mode = SOLO_ENC_MODE_CIF;
1315 	solo_enc->motion_global = true;
1316 	solo_enc->motion_thresh = SOLO_DEF_MOT_THRESH;
1317 	solo_enc->vidq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1318 	solo_enc->vidq.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1319 	solo_enc->vidq.ops = &solo_enc_video_qops;
1320 	solo_enc->vidq.mem_ops = &vb2_dma_sg_memops;
1321 	solo_enc->vidq.drv_priv = solo_enc;
1322 	solo_enc->vidq.gfp_flags = __GFP_DMA32;
1323 	solo_enc->vidq.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1324 	solo_enc->vidq.buf_struct_size = sizeof(struct solo_vb2_buf);
1325 	solo_enc->vidq.lock = &solo_enc->lock;
1326 	ret = vb2_queue_init(&solo_enc->vidq);
1327 	if (ret)
1328 		goto hdl_free;
1329 	solo_update_mode(solo_enc);
1330 
1331 	spin_lock_init(&solo_enc->motion_lock);
1332 
1333 	/* Initialize this per encoder */
1334 	solo_enc->jpeg_len = sizeof(jpeg_header);
1335 	memcpy(solo_enc->jpeg_header, jpeg_header, solo_enc->jpeg_len);
1336 
1337 	solo_enc->desc_nelts = 32;
1338 	solo_enc->desc_items = pci_alloc_consistent(solo_dev->pdev,
1339 				      sizeof(struct solo_p2m_desc) *
1340 				      solo_enc->desc_nelts,
1341 				      &solo_enc->desc_dma);
1342 	ret = -ENOMEM;
1343 	if (solo_enc->desc_items == NULL)
1344 		goto hdl_free;
1345 
1346 	solo_enc->vfd = video_device_alloc();
1347 	if (!solo_enc->vfd)
1348 		goto pci_free;
1349 
1350 	*solo_enc->vfd = solo_enc_template;
1351 	solo_enc->vfd->v4l2_dev = &solo_dev->v4l2_dev;
1352 	solo_enc->vfd->ctrl_handler = hdl;
1353 	solo_enc->vfd->queue = &solo_enc->vidq;
1354 	solo_enc->vfd->lock = &solo_enc->lock;
1355 	video_set_drvdata(solo_enc->vfd, solo_enc);
1356 	ret = video_register_device(solo_enc->vfd, VFL_TYPE_GRABBER, nr);
1357 	if (ret < 0)
1358 		goto vdev_release;
1359 
1360 	snprintf(solo_enc->vfd->name, sizeof(solo_enc->vfd->name),
1361 		 "%s-enc (%i/%i)", SOLO6X10_NAME, solo_dev->vfd->num,
1362 		 solo_enc->vfd->num);
1363 
1364 	return solo_enc;
1365 
1366 vdev_release:
1367 	video_device_release(solo_enc->vfd);
1368 pci_free:
1369 	pci_free_consistent(solo_enc->solo_dev->pdev,
1370 			sizeof(struct solo_p2m_desc) * solo_enc->desc_nelts,
1371 			solo_enc->desc_items, solo_enc->desc_dma);
1372 hdl_free:
1373 	v4l2_ctrl_handler_free(hdl);
1374 	vb2_dma_sg_cleanup_ctx(solo_enc->alloc_ctx);
1375 	kfree(solo_enc);
1376 	return ERR_PTR(ret);
1377 }
1378 
1379 static void solo_enc_free(struct solo_enc_dev *solo_enc)
1380 {
1381 	if (solo_enc == NULL)
1382 		return;
1383 
1384 	pci_free_consistent(solo_enc->solo_dev->pdev,
1385 			sizeof(struct solo_p2m_desc) * solo_enc->desc_nelts,
1386 			solo_enc->desc_items, solo_enc->desc_dma);
1387 	video_unregister_device(solo_enc->vfd);
1388 	v4l2_ctrl_handler_free(&solo_enc->hdl);
1389 	vb2_dma_sg_cleanup_ctx(solo_enc->alloc_ctx);
1390 	kfree(solo_enc);
1391 }
1392 
1393 int solo_enc_v4l2_init(struct solo_dev *solo_dev, unsigned nr)
1394 {
1395 	int i;
1396 
1397 	init_waitqueue_head(&solo_dev->ring_thread_wait);
1398 
1399 	solo_dev->vh_size = sizeof(vop_header);
1400 	solo_dev->vh_buf = pci_alloc_consistent(solo_dev->pdev,
1401 						solo_dev->vh_size,
1402 						&solo_dev->vh_dma);
1403 	if (solo_dev->vh_buf == NULL)
1404 		return -ENOMEM;
1405 
1406 	for (i = 0; i < solo_dev->nr_chans; i++) {
1407 		solo_dev->v4l2_enc[i] = solo_enc_alloc(solo_dev, i, nr);
1408 		if (IS_ERR(solo_dev->v4l2_enc[i]))
1409 			break;
1410 	}
1411 
1412 	if (i != solo_dev->nr_chans) {
1413 		int ret = PTR_ERR(solo_dev->v4l2_enc[i]);
1414 
1415 		while (i--)
1416 			solo_enc_free(solo_dev->v4l2_enc[i]);
1417 		pci_free_consistent(solo_dev->pdev, solo_dev->vh_size,
1418 				    solo_dev->vh_buf, solo_dev->vh_dma);
1419 		solo_dev->vh_buf = NULL;
1420 		return ret;
1421 	}
1422 
1423 	if (solo_dev->type == SOLO_DEV_6010)
1424 		solo_dev->enc_bw_remain = solo_dev->fps * 4 * 4;
1425 	else
1426 		solo_dev->enc_bw_remain = solo_dev->fps * 4 * 5;
1427 
1428 	dev_info(&solo_dev->pdev->dev, "Encoders as /dev/video%d-%d\n",
1429 		 solo_dev->v4l2_enc[0]->vfd->num,
1430 		 solo_dev->v4l2_enc[solo_dev->nr_chans - 1]->vfd->num);
1431 
1432 	return solo_ring_start(solo_dev);
1433 }
1434 
1435 void solo_enc_v4l2_exit(struct solo_dev *solo_dev)
1436 {
1437 	int i;
1438 
1439 	solo_ring_stop(solo_dev);
1440 
1441 	for (i = 0; i < solo_dev->nr_chans; i++)
1442 		solo_enc_free(solo_dev->v4l2_enc[i]);
1443 
1444 	if (solo_dev->vh_buf)
1445 		pci_free_consistent(solo_dev->pdev, solo_dev->vh_size,
1446 			    solo_dev->vh_buf, solo_dev->vh_dma);
1447 }
1448