ahci_elphel.c 58.1 KB
Newer Older
Mikhail Karpenko's avatar
Mikhail Karpenko committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Elphel AHCI SATA platform driver for elphel393 camera
 *
 * Based on the AHCI SATA platform driver by Jeff Garzik and Anton Vorontsov
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 */

16
/* this one is required for printk_ratelimited */
17 18
#define CONFIG_PRINK

Mikhail Karpenko's avatar
Mikhail Karpenko committed
19 20 21 22 23 24
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/ahci_platform.h>
#include <linux/of.h>
#include <linux/of_device.h>
25
#include <linux/of_address.h>
Mikhail Karpenko's avatar
Mikhail Karpenko committed
26 27 28
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
29
#include <linux/sysfs.h>
30 31
#include <elphel/exifa.h>
#include <elphel/elphel393-mem.h>
32

Mikhail Karpenko's avatar
Mikhail Karpenko committed
33
#include "ahci.h"
34 35 36
#include "ahci_elphel.h"
#include "../elphel/exif393.h"
#include "../elphel/jpeghead.h"
Mikhail Karpenko's avatar
Mikhail Karpenko committed
37 38

#define DRV_NAME "elphel-ahci"
39 40 41 42 43 44
/*
 * FPGA bitstream control address and bit mask. These are used to check whether
 * bitstream is loaded or not.
 */
#define BITSTREAM_CTRL_ADDR	0xf800700c
#define BITSTREAM_CTRL_BIT	0x4
Mikhail Karpenko's avatar
Mikhail Karpenko committed
45 46 47 48 49 50 51 52 53

/* Property names from device tree, these are specific for the controller */
#define PROP_NAME_CLB_OFFS "clb_offs"
#define PROP_NAME_FB_OFFS "fb_offs"

static struct ata_port_operations ahci_elphel_ops;
static const struct ata_port_info ahci_elphel_port_info;
static struct scsi_host_template ahci_platform_sht;
static const struct of_device_id ahci_elphel_of_match[];
54 55 56
static const struct attribute_group dev_attr_root_group;

static bool load_driver = false;
57
static unsigned char app15[ALIGNMENT_SIZE] = {0xff, 0xef};
Mikhail Karpenko's avatar
Mikhail Karpenko committed
58

59 60
static void elphel_cmd_issue(struct ata_port *ap, uint64_t start, uint16_t count, struct fvec *sgl, unsigned int elem, uint8_t cmd);
static int init_buffers(struct device *dev, struct frame_buffers *buffs);
61
static void init_vectors(struct frame_buffers *buffs, struct fvec *chunks);
62 63
static void deinit_buffers(struct device *dev, struct frame_buffers *buffs);
static inline struct elphel_ahci_priv *dev_get_dpriv(struct device *dev);
64 65 66
static void finish_cmd(struct elphel_ahci_priv *dpriv);
static void finish_rec(struct elphel_ahci_priv *dpriv);
static int process_cmd(struct elphel_ahci_priv *dpriv);
67
static inline size_t get_size_from(const struct fvec *vects, int index, size_t offset, int all);
68 69
static inline void vectmov(struct fvec *vec, size_t len);
static inline void vectsplit(struct fvec *vect, struct fvec *parts, size_t *n_elem);
70 71 72 73
static int move_tail(struct elphel_ahci_priv *dpriv);
static int move_head(struct elphel_ahci_priv *dpriv);
static size_t get_prev_slot(const struct elphel_ahci_priv *dpriv);
static int is_cmdq_empty(const struct elphel_ahci_priv *dpriv);
74
void process_queue(unsigned long data);
75 76
static void set_flag(struct elphel_ahci_priv *drpiv, uint32_t flag);
static void reset_flag(struct elphel_ahci_priv *dpriv, uint32_t flag);
77
static inline void reset_chunks(struct fvec *vects, int all);
78 79 80
/* debug functions */
static int check_chunks(struct fvec *vects);
static void dump_sg_list(const struct device *dev, const struct fvec *sgl, size_t elems);
81 82 83
static void dump_sg_list_uncond(const struct fvec *sgl, size_t elems);
static void dump_iomem(void __iomem *mmio);
static void dump_dpriv_fields(struct elphel_ahci_priv *dpriv);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
static ssize_t set_load_flag(struct device *dev, struct device_attribute *attr,
		const char *buff, size_t buff_sz)
{
	load_driver = true;

	return buff_sz;
}

static int bitstream_loaded(u32 *ptr)
{
	u32 val = ioread32(ptr);

	if (val & BITSTREAM_CTRL_BIT)
		return 1;
	else
		return 0;
}

103
static void elphel_defer_load(struct device *dev)
104
{
105
	bool check_flag = true;
106 107
	u32 *ctrl_ptr = ioremap_nocache(BITSTREAM_CTRL_ADDR, 4);

108 109 110 111 112 113 114 115 116 117 118 119 120 121
	dev_info(dev, "AHCI driver loading is deferred. Load bitstream and write 1 into "
			"/sys/devices/soc0/amba@0/80000000.elphel-ahci/load_module to continue\n");
	while (check_flag) {
		if (load_driver) {
			if (bitstream_loaded(ctrl_ptr)) {
				check_flag = false;
			} else {
				dev_err(dev, "FPGA bitstream is not loaded or bitstream "
						"does not contain AHCI controller\n");
				load_driver = false;
			}
		} else {
			msleep(1000);
		}
122
	}
123
	load_driver = false;
124 125 126
	iounmap(ctrl_ptr);
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
/** Set command execution timer. This function is called before every internal command and
 * the command is considered stalled if the timer has expired. */
static void set_timer(struct elphel_ahci_priv *dpriv)
{
	unsigned long timeout = jiffies + msecs_to_jiffies(dpriv->cmd_timeout);
	mod_timer(&dpriv->cmd_timer, timeout);
}

/** Remove command execution timer if it is still running */
static void remove_timer(struct elphel_ahci_priv *dpriv)
{
	int ret;

	if (timer_pending(&dpriv->cmd_timer)) {
		ret = del_timer_sync(&dpriv->cmd_timer);
		if (ret < 0)
			dev_err(dpriv->dev, "can not remove timer\n");
	}
}

/** This command resets all commands and flags indicating current state of the driver */
static void reset_all_commands(struct elphel_ahci_priv *dpriv)
{
	int i;
	unsigned long irq_flags;

	if (is_cmdq_empty(dpriv))
		return;

	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
	for (i = 0; i < MAX_CMD_SLOTS; i++) {
		reset_chunks(dpriv->data_chunks[i], 1);
	}
	dpriv->flags = 0;
	dpriv->head_ptr = 0;
	dpriv->tail_ptr = 0;

	dpriv->lba_ptr.wr_count = 0;
	dpriv->curr_cmd = 0;
	dpriv->max_data_sz = 0;
	dpriv->curr_data_chunk = 0;
	dpriv->curr_data_offset = 0;
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
}

/** Command execution timer has expired, set flag indicating that recording should be restarted */
static void process_timeout(unsigned long data)
{
	struct elphel_ahci_priv *dpriv = (struct elphel_ahci_priv *)data;

	printk(KERN_ERR "AHCI error: command execution timeout\n");
	set_flag(dpriv, START_EH);
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
/** Calculate the difference between two time stamps and return it in microseconds */
static unsigned long time_diff_usec(sec_usec_t *start_time, sec_usec_t *end_time)
{
	unsigned long time_us;
	const unsigned long scale = 1000000;

	if (start_time->sec <= end_time->sec) {
		time_us = (end_time->sec - start_time->sec) * scale;
	} else {
		// time counter has rolled over
		time_us = (ULONG_MAX - start_time->sec + end_time->sec) * scale;
	}
	if (start_time->usec <= end_time->usec)
		time_us += end_time->usec - start_time->usec;
	else
		time_us += scale - start_time->usec + end_time->usec;

	return time_us;
}

/** Add new recording speed sample to the list of samples */
static void add_sample(unsigned int sample, struct rec_stat *stat)
{
	stat->samples[stat->samples_ptr] = sample;
	stat->samples_ptr++;
	if (stat->samples_ptr >= SPEED_SAMPLES_NUM) {
		stat->samples_ptr = 0;
	}
}

211 212
static irqreturn_t elphel_irq_handler(int irq, void * dev_instance)
{
213
	unsigned long irq_flags;
214 215 216 217 218 219 220 221 222 223
	irqreturn_t handled;
	struct ata_host *host = dev_instance;
	struct ahci_host_priv *hpriv = host->private_data;
	struct ata_port *port = host->ports[DEFAULT_PORT_NUM];
	void __iomem *port_mmio = ahci_port_base(port);
	struct elphel_ahci_priv *dpriv = hpriv->plat_data;
	uint32_t irq_stat, host_irq_stat;


	if (dpriv->flags & IRQ_SIMPLE) {
224
		/* handle interrupt from internal command */
225 226 227 228 229 230
		host_irq_stat = readl(hpriv->mmio + HOST_IRQ_STAT);
		if (!host_irq_stat)
			return IRQ_NONE;
		dpriv->flags &= ~IRQ_SIMPLE;
		irq_stat = readl(port_mmio + PORT_IRQ_STAT);

231
		dev_dbg(host->dev, "irq_stat = 0x%x, host irq_stat = 0x%x\n", irq_stat, host_irq_stat);
232

233
		writel(irq_stat, port_mmio + PORT_IRQ_STAT);
234 235
		writel(host_irq_stat, hpriv->mmio + HOST_IRQ_STAT);
		handled = IRQ_HANDLED;
236
		tasklet_schedule(&dpriv->bh);
237
	} else {
238
		/* pass handling to AHCI level and then decide if the resource should be freed */
239
		handled = ahci_single_irq_intr(irq, dev_instance);
240 241 242 243 244 245 246
		spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
		if (is_cmdq_empty(dpriv)) {
			dpriv->flags &= ~DISK_BUSY;
		} else {
			tasklet_schedule(&dpriv->bh);
		}
		spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
247 248 249 250
	}

	return handled;
}
251
/** Command queue processing tasklet */
252 253
void process_queue(unsigned long data)
{
254 255
	int i;
	size_t total_sz = 0;
256
	unsigned long irq_flags;
257 258
	unsigned long time_usec;
	sec_usec_t end_time = {0};
259 260
	struct elphel_ahci_priv *dpriv = (struct elphel_ahci_priv *)data;

261 262 263 264 265 266 267 268 269
	// calculate the speed this frame has been written with
	get_fpga_rtc(&end_time);
	time_usec = time_diff_usec(&dpriv->stat.start_time, &end_time);
	if (time_usec != 0) {
		for (i = 0; i < dpriv->sg_elems; i++)
			total_sz += dpriv->sgl[i].iov_len;
		add_sample(total_sz / time_usec, &dpriv->stat);
	}

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	if (process_cmd(dpriv) == 0) {
		finish_cmd(dpriv);
		if (move_head(dpriv) != -1) {
			process_cmd(dpriv);
		} else {
			if (dpriv->flags & DELAYED_FINISH) {
				dpriv->flags &= ~DELAYED_FINISH;
				finish_rec(dpriv);
			} else {
				/* all commands have been processed */
				spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
				dpriv->flags &= ~DISK_BUSY;
				spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
			}
		}
	}
}

288 289
// What about port_stop and freeing/unmapping ?
// Or at least check if it is re-started and memory is already allocated/mapped
Mikhail Karpenko's avatar
Mikhail Karpenko committed
290 291 292 293 294 295 296 297 298
static int elphel_port_start(struct ata_port *ap)
{
	void *mem;
	dma_addr_t mem_dma;
	struct device *dev = ap->host->dev;
	struct ahci_port_priv *pp;
	struct ahci_host_priv *hpriv = ap->host->private_data;
	const struct elphel_ahci_priv *dpriv = hpriv->plat_data;

299
	dev_dbg(dev, "starting port %d", ap->port_no);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
300
	pp = devm_kzalloc(dev, sizeof(struct ahci_port_priv), GFP_KERNEL);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
301 302 303
	if (!pp)
		return -ENOMEM;

304
	mem = devm_kmalloc(dev, 0x100000, GFP_KERNEL); // AHCI_CMD_TBL_AR_SZ = 0x16000
Mikhail Karpenko's avatar
Mikhail Karpenko committed
305 306
	if (!mem)
		return -ENOMEM;
307 308
	mem_dma = dma_map_single(dev, mem, AHCI_CMD_TBL_AR_SZ, DMA_TO_DEVICE); // maybe DMA_BIDIRECTIONAL, but currently we do not use DMA for received FISes

309 310
	pp->cmd_tbl = mem;
	pp->cmd_tbl_dma = mem_dma;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
311 312 313 314

	/*
	 * Set predefined addresses
	 */
Mikhail Karpenko's avatar
Mikhail Karpenko committed
315
	pp->cmd_slot = hpriv->mmio + dpriv->clb_offs;
316
	pp->cmd_slot_dma = dpriv->base_addr + dpriv->clb_offs;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
317 318

	pp->rx_fis = hpriv->mmio + dpriv->fb_offs;
319
	pp->rx_fis_dma = dpriv->base_addr + dpriv->fb_offs;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
320 321 322 323 324

	/*
	 * Save off initial list of interrupts to be enabled.
	 * This could be changed later
	 */
Mikhail Karpenko's avatar
Mikhail Karpenko committed
325
	pp->intr_mask = DEF_PORT_IRQ;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
326 327 328

	ap->private_data = pp;

Mikhail Karpenko's avatar
Mikhail Karpenko committed
329
	return ahci_port_resume(ap);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
330 331 332 333 334 335
}

static int elphel_parse_prop(const struct device_node *devn,
		struct device *dev,
		struct elphel_ahci_priv *dpriv)
{
336
	int rc = 0;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
337
	const __be32 *val;
338
	struct resource res;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
339 340

	if (!devn) {
341
		dev_err(dev, "elphel-ahci device tree node is not found");
Mikhail Karpenko's avatar
Mikhail Karpenko committed
342 343 344 345
		return -EINVAL;
	}

	val = of_get_property(devn, PROP_NAME_CLB_OFFS, NULL);
346 347 348 349
	if (!val) {
		dev_err(dev, "can not find clb_offs in device tree");
		return -EINVAL;
	}
Mikhail Karpenko's avatar
Mikhail Karpenko committed
350
	dpriv->clb_offs = be32_to_cpup(val);
351

Mikhail Karpenko's avatar
Mikhail Karpenko committed
352
	val = of_get_property(devn, PROP_NAME_FB_OFFS, NULL);
353 354 355 356
	if (!val) {
		dev_err(dev, "can not find fb_offs in device tree");
		return -EINVAL;
	}
Mikhail Karpenko's avatar
Mikhail Karpenko committed
357
	dpriv->fb_offs = be32_to_cpup(val);
358 359 360 361 362

	rc = of_address_to_resource((struct device_node *)devn, 0, &res);
	if (rc < 0) {
		dev_err(dev, "can not find address in device tree");
		return -EINVAL;
363
	}
364
	dpriv->base_addr = (u32)res.start;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
365 366 367 368 369 370

	return 0;
}

static int elphel_drv_probe(struct platform_device *pdev)
{
371
	int ret, i, irq_num;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
372
	struct ahci_host_priv *hpriv;
373
	struct elphel_ahci_priv *dpriv;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
374 375
	struct device *dev = &pdev->dev;
	const struct of_device_id *match;
376
	struct ata_host *host;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
377

378 379 380 381 382
	if (&dev->kobj) {
		ret = sysfs_create_group(&dev->kobj, &dev_attr_root_group);
		if (ret < 0)
			return ret;
	}
383
	elphel_defer_load(dev);
384

Mikhail Karpenko's avatar
Mikhail Karpenko committed
385
	dev_info(&pdev->dev, "probing Elphel AHCI driver");
386

387 388
	dpriv = devm_kzalloc(dev, sizeof(struct elphel_ahci_priv), GFP_KERNEL);
	if (!dpriv)
Mikhail Karpenko's avatar
Mikhail Karpenko committed
389 390
		return -ENOMEM;

391
	dpriv->dev = dev;
392
	spin_lock_init(&dpriv->flags_lock);
393
	tasklet_init(&dpriv->bh, process_queue, (unsigned long)dpriv);
394 395
	setup_timer(&dpriv->cmd_timer, process_timeout, (unsigned long)dpriv);
	dpriv->cmd_timeout = DEFAULT_CMD_TIMEOUT;
396

397 398 399 400
	for (i = 0; i < MAX_CMD_SLOTS; i++) {
		ret = init_buffers(dev, &dpriv->fbuffs[i]);
		if (ret != 0)
			return ret;
401
		init_vectors(&dpriv->fbuffs[i], dpriv->data_chunks[i]);
402
	}
403

Mikhail Karpenko's avatar
Mikhail Karpenko committed
404 405 406 407
	match = of_match_device(ahci_elphel_of_match, &pdev->dev);
	if (!match)
		return -EINVAL;

408
	ret = elphel_parse_prop(dev->of_node, dev, dpriv);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
409 410 411
	if (ret != 0)
		return ret;

Mikhail Karpenko's avatar
Mikhail Karpenko committed
412
	hpriv = ahci_platform_get_resources(pdev);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
413 414 415
	if (IS_ERR(hpriv))
		return PTR_ERR(hpriv);

416
	hpriv->plat_data = dpriv;
Mikhail Karpenko's avatar
Mikhail Karpenko committed
417

Mikhail Karpenko's avatar
Mikhail Karpenko committed
418
	ret = ahci_platform_init_host(pdev, hpriv, &ahci_elphel_port_info,
Mikhail Karpenko's avatar
Mikhail Karpenko committed
419 420
			&ahci_platform_sht);
	if (ret) {
Mikhail Karpenko's avatar
Mikhail Karpenko committed
421
		dev_err(dev, "can not initialize platform host");
Mikhail Karpenko's avatar
Mikhail Karpenko committed
422 423 424 425
		ahci_platform_disable_resources(hpriv);
		return ret;
	}

426 427 428 429 430 431 432 433
	/* reassign automatically assigned interrupt handler */
	irq_num = platform_get_irq(pdev, 0);
	host = platform_get_drvdata(pdev);
	devm_free_irq(dev, irq_num, host);
	ret = devm_request_irq(dev, irq_num, elphel_irq_handler, IRQF_SHARED, dev_name(dev), host);
	if (ret) {
		dev_err(dev, "failed to reassign default IRQ handler to Elphel handler\n");
		return ret;
434
	}
Mikhail Karpenko's avatar
Mikhail Karpenko committed
435 436 437 438 439 440

	return 0;
}

static int elphel_drv_remove(struct platform_device *pdev)
{
441
	int i;
442 443
	struct elphel_ahci_priv *dpriv = dev_get_dpriv(&pdev->dev);

Mikhail Karpenko's avatar
Mikhail Karpenko committed
444
	dev_info(&pdev->dev, "removing Elphel AHCI driver");
445
	tasklet_kill(&dpriv->bh);
446
	remove_timer(dpriv);
447 448
	for (i = 0; i < MAX_CMD_SLOTS; i++)
		deinit_buffers(&pdev->dev, &dpriv->fbuffs[i]);
449
	sysfs_remove_group(&pdev->dev.kobj, &dev_attr_root_group);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
450 451 452 453 454
	ata_platform_remove_one(pdev);

	return 0;
}

455
static void elphel_qc_prep(struct ata_queued_cmd *qc)
Mikhail Karpenko's avatar
Mikhail Karpenko committed
456
{
457 458 459 460 461 462 463 464 465 466
	struct ata_port *ap = qc->ap;
	struct ahci_port_priv *pp = ap->private_data;
	int is_atapi = ata_is_atapi(qc->tf.protocol);
	void *cmd_tbl;
	u32 opts;
	const u32 cmd_fis_len = 5; /* five dwords */
	unsigned int n_elem;
	struct scatterlist *sg;
	struct ahci_sg *ahci_sg;

467 468 469
	/* There is only one slot in controller thus we need to change tag*/
	qc->tag = 0;

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	/*
	 * Fill in command table information.  First, the header,
	 * a SATA Register - Host to Device command FIS.
	 */
	dma_sync_single_for_cpu(&qc->dev->tdev, pp->cmd_tbl_dma,
			AHCI_CMD_TBL_AR_SZ, DMA_TO_DEVICE);
	cmd_tbl = pp->cmd_tbl + qc->tag * AHCI_CMD_TBL_SZ;

	ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, cmd_tbl);

	if (is_atapi) {
		memset(cmd_tbl + AHCI_CMD_TBL_CDB, 0, 32);
		memcpy(cmd_tbl + AHCI_CMD_TBL_CDB, qc->cdb, qc->dev->cdb_len);
	}

	/*
	 * Next, the S/G list.
	 */
	n_elem = 0;
	ahci_sg = cmd_tbl + AHCI_CMD_TBL_HDR_SZ;
	if (qc->flags & ATA_QCFLAG_DMAMAP) {
		for_each_sg(qc->sg, sg, qc->n_elem, n_elem) {
			dma_addr_t addr = sg_dma_address(sg);
			u32 sg_len = sg_dma_len(sg);

			ahci_sg[n_elem].addr = cpu_to_le32(addr & 0xffffffff);
			ahci_sg[n_elem].addr_hi = cpu_to_le32((addr >> 16) >> 16);
			ahci_sg[n_elem].flags_size = cpu_to_le32(sg_len - 1);
		}
499
	}
Mikhail Karpenko's avatar
Mikhail Karpenko committed
500

501 502 503 504 505 506 507 508 509 510 511 512
	/*
	 * Fill in command slot information.
	 */
	opts = cmd_fis_len | n_elem << 16 | (qc->dev->link->pmp << 12);
	if (qc->tf.flags & ATA_TFLAG_WRITE)
		opts |= AHCI_CMD_WRITE;
	if (is_atapi)
		opts |= AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH;

	ahci_fill_cmd_slot(pp, qc->tag, opts);
	dma_sync_single_for_device(&qc->dev->tdev, pp->cmd_tbl_dma,
			AHCI_CMD_TBL_AR_SZ, DMA_TO_DEVICE);
Mikhail Karpenko's avatar
Mikhail Karpenko committed
513 514
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
/** Set flag @e flag in driver private structure. This function uses spin lock to access the flags variable. */
static void set_flag(struct elphel_ahci_priv *dpriv, uint32_t flag)
{
	unsigned long irq_flags;

	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
	dpriv->flags |= flag;
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
}

/** Reset flag @e flag in driver private structure. This function uses spin lock to access the flags variable. */
static void reset_flag(struct elphel_ahci_priv *dpriv, uint32_t flag)
{
	unsigned long irq_flags;

	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
	dpriv->flags &= ~flag;
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
}

535 536 537 538 539 540 541 542
/** Map buffer vectors to S/G list and return the number of vectors mapped */
static int map_vectors(struct elphel_ahci_priv *dpriv)
{
	int i;
	int index = 0;
	int finish = 0;
	size_t total_sz = 0;
	size_t tail;
543
	struct fvec *chunks;
544 545
	struct fvec vect;

546
	chunks = dpriv->data_chunks[dpriv->head_ptr];
547 548 549 550 551 552 553 554 555 556 557 558 559 560
	for (i = dpriv->curr_data_chunk; i < MAX_DATA_CHUNKS; i++) {
		if (i == CHUNK_REM)
			/* remainder should never be processed */
			continue;
		if (i == dpriv->curr_data_chunk) {
			total_sz = chunks[i].iov_len - dpriv->curr_data_offset;
			vect.iov_base = (unsigned char *)chunks[i].iov_base + dpriv->curr_data_offset;
			vect.iov_dma = chunks[i].iov_dma + dpriv->curr_data_offset;
			vect.iov_len = chunks[i].iov_len - dpriv->curr_data_offset;
		} else {
			total_sz += chunks[i].iov_len;
			vect = chunks[i];
		}
		if (total_sz > dpriv->max_data_sz) {
561
			/* truncate current buffer and finish mapping */
562 563 564 565 566 567 568 569 570 571 572
			tail = total_sz - dpriv->max_data_sz;
			vect.iov_len -= tail;
			dpriv->curr_data_chunk = i;
			dpriv->curr_data_offset = chunks[i].iov_len - tail;
			finish = 1;
		} else if (unlikely(total_sz == dpriv->max_data_sz)) {
			dpriv->curr_data_chunk = i;
			dpriv->curr_data_offset = chunks[i].iov_len;
			finish = 1;
		}
		if (vect.iov_len != 0) {
573 574 575 576 577 578 579 580 581 582 583 584 585 586
			if (vect.iov_len < MAX_PRDT_LEN) {
				dpriv->sgl[index++] = vect;
			} else {
				/* current vector is too long and can not be mapped to a single PRDT entry, split it */
				vectsplit(&vect, dpriv->sgl, &index);
				if (vect.iov_len < MAX_PRDT_LEN) {
					dpriv->sgl[index++] = vect;
				} else {
					/* free slots in PRDT table have ended */
					dpriv->curr_data_chunk = i;
					dpriv->curr_data_offset = (unsigned char *)vect.iov_base - (unsigned char *)chunks[i].iov_base;
					finish = 1;
				}
			}
587 588
			if (index == (MAX_SGL_LEN - 1))
				finish = 1;
589 590 591 592 593
		}
		if (finish)
			break;
	}
	if (finish == 0) {
Mikhail Karpenko's avatar
Mikhail Karpenko committed
594
		/* frame vectors have been fully processed, stop calling me */
595 596 597 598 599 600 601
		dpriv->curr_data_chunk = MAX_DATA_CHUNKS;
		dpriv->curr_data_offset = 0;
	}

	return index;
}

602
/** Split buffer pointed by vector @e vect into several smaller buffer. Each part will be less than #MAX_PRDT_LEN bytes */
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
static inline void vectsplit(struct fvec *vect, struct fvec *parts, size_t *n_elem)
{
	size_t len;
	struct fvec split;

	while (vect->iov_len > MAX_PRDT_LEN && *n_elem < MAX_SGL_LEN) {
		len = MAX_PRDT_LEN - MAX_PRDT_LEN % PHY_BLOCK_SIZE;
		split.iov_base = vect->iov_base;
		split.iov_dma = vect->iov_dma;
		split.iov_len = len;
		vectmov(vect, len);
		parts[*n_elem] = split;
		*n_elem = *n_elem + 1;
	}
}
618 619

/** Copy @e len bytes from buffer pointed by @e src vector to buffer pointed by @e dest vector */
620 621 622 623 624 625 626
static inline void vectcpy(struct fvec *dest, void *src, size_t len)
{
	unsigned char *d = (unsigned char *)dest->iov_base;

	memcpy(d + dest->iov_len, src, len);
	dest->iov_len += len;
}
627 628

/** Move vector forward by @e len bytes decreasing its length */
629 630 631 632 633 634 635 636
static inline void vectmov(struct fvec *vec, size_t len)
{
	if (vec->iov_len >= len) {
		vec->iov_base = (unsigned char *)vec->iov_base + len;
		vec->iov_dma += len;
		vec->iov_len -= len;
	}
}
637 638

/** Shrink vector length by @len bytes */
639 640 641 642 643 644
static inline void vectshrink(struct fvec *vec, size_t len)
{
	if (vec->iov_len >= len) {
		vec->iov_len -= len;
	}
}
645 646

/** Return the number of bytes needed to align @e data_len to @e align_len boundary */
647 648 649 650 651 652 653 654
static inline size_t align_bytes_num(size_t data_len, size_t align_len)
{
	size_t rem = data_len % align_len;
	if (rem == 0)
		return 0;
	else
		return align_len - rem;
}
655

656 657 658 659 660 661
/** This helper function is used to position a pointer @e offset bytes from the end
 * of a buffer. DMA handle is not updated intentionally as it is not needed during copying */
static inline unsigned char *vectrpos(struct fvec *vec, size_t offset)
{
	return (unsigned char *)vec->iov_base + (vec->iov_len - offset);
}
662 663

/** Align current frame to disk sector boundary and each individual buffer to #ALIGNMENT_SIZE boundary */
664
static void align_frame(struct elphel_ahci_priv *dpriv)
665 666 667
{
	unsigned char *src;
	size_t len, total_sz, data_len;
668 669 670
	size_t cmd_slot = dpriv->tail_ptr;
	size_t prev_slot = get_prev_slot(dpriv);
	size_t max_len = dpriv->fbuffs[cmd_slot].common_buff.iov_len;
671
	struct device *dev = dpriv->dev;
672
	struct frame_buffers *fbuffs = &dpriv->fbuffs[cmd_slot];
673
	struct fvec *chunks = dpriv->data_chunks[cmd_slot];
674
	struct fvec *cbuff = &chunks[CHUNK_COMMON];
675
	struct fvec *rbuff = &dpriv->data_chunks[prev_slot][CHUNK_REM];
676

677
	total_sz = get_size_from(chunks, 0, 0, INCLUDE_REM) + rbuff->iov_len;
678 679
	if (total_sz < PHY_BLOCK_SIZE) {
		/* the frame length is less than sector size, delay this frame */
680 681 682 683 684
		if (prev_slot != cmd_slot) {
			/* some data may be left from previous frame */
			vectcpy(&chunks[CHUNK_REM], rbuff->iov_base, rbuff->iov_len);
			vectshrink(rbuff, rbuff->iov_len);
		}
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
		dev_dbg(dev, "frame size is less than sector size: %u bytes; delay recording\n", total_sz);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_LEADER].iov_base, chunks[CHUNK_LEADER].iov_len);
		vectshrink(&chunks[CHUNK_LEADER], chunks[CHUNK_LEADER].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_EXIF].iov_base, chunks[CHUNK_EXIF].iov_len);
		vectshrink(&chunks[CHUNK_EXIF], chunks[CHUNK_EXIF].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_HEADER].iov_base, chunks[CHUNK_HEADER].iov_len);
		vectshrink(&chunks[CHUNK_HEADER], chunks[CHUNK_HEADER].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_0].iov_base, chunks[CHUNK_DATA_0].iov_len);
		vectshrink(&chunks[CHUNK_DATA_0], chunks[CHUNK_DATA_0].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_1].iov_base, chunks[CHUNK_DATA_1].iov_len);
		vectshrink(&chunks[CHUNK_DATA_1], chunks[CHUNK_DATA_1].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
		vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
		return;
	}

	dma_sync_single_for_cpu(dev, fbuffs->common_buff.iov_dma, fbuffs->common_buff.iov_len, DMA_TO_DEVICE);

	/* copy remainder of previous frame to the beginning of common buffer */
704 705 706 707 708
	if (likely(rbuff->iov_len != 0)) {
		len = rbuff->iov_len;
		dev_dbg(dev, "copy %u bytes from REM #%u to common buffer\n", len, prev_slot);
		vectcpy(cbuff, rbuff->iov_base, len);
		vectshrink(rbuff, rbuff->iov_len);
709 710 711 712 713 714 715 716 717 718
	}

	/* copy JPEG marker */
	len = chunks[CHUNK_LEADER].iov_len;
	vectcpy(cbuff, chunks[CHUNK_LEADER].iov_base, len);
	vectshrink(&chunks[CHUNK_LEADER], chunks[CHUNK_LEADER].iov_len);

	/* copy Exif if present */
	if (chunks[CHUNK_EXIF].iov_len != 0) {
		len = chunks[CHUNK_EXIF].iov_len;
719
		dev_dbg(dev, "copy %u bytes from EXIF to common buffer\n", len);
720 721 722 723
		vectcpy(cbuff, chunks[CHUNK_EXIF].iov_base, len);
		vectshrink(&chunks[CHUNK_EXIF], chunks[CHUNK_EXIF].iov_len);
	}

724 725 726 727 728 729 730 731 732 733 734
	/* align common buffer to ALIGNMENT boundary, APP15 marker should be placed before header data */
	data_len = cbuff->iov_len + chunks[CHUNK_HEADER].iov_len;
	len = align_bytes_num(data_len, ALIGNMENT_SIZE);
	if (len < JPEG_MARKER_LEN + JPEG_SIZE_LEN && len != 0) {
		/* the number of bytes needed for alignment is less than the length of the marker itself, increase the number of stuffing bytes */
		len += ALIGNMENT_SIZE;
	}
	dev_dbg(dev, "total number of stuffing bytes in APP15 marker: %u\n", len);
	app15[3] = len - JPEG_MARKER_LEN;
	vectcpy(cbuff, app15, len);

735 736
	/* copy JPEG header */
	len = chunks[CHUNK_HEADER].iov_len;
737
	dev_dbg(dev, "copy %u bytes from HEADER to common buffer\n", len);
738 739 740
	vectcpy(cbuff, chunks[CHUNK_HEADER].iov_base, len);
	vectshrink(&chunks[CHUNK_HEADER], chunks[CHUNK_HEADER].iov_len);

741 742
	/* check if there is enough data to continue - JPEG data length can be too short */
	len = get_size_from(chunks, CHUNK_DATA_0, 0, EXCLUDE_REM);
743
	if (len < PHY_BLOCK_SIZE) {
744
		size_t num = align_bytes_num(cbuff->iov_len, PHY_BLOCK_SIZE);
745
		dev_dbg(dev, "jpeg data is too short, delay this frame\n");
746 747 748
		if (len >= num) {
			/* there is enough data to align common buffer to sector boundary */
			if (num >= chunks[CHUNK_DATA_0].iov_len) {
749
				vectcpy(cbuff, chunks[CHUNK_DATA_0].iov_base, chunks[CHUNK_DATA_0].iov_len);
750
				num -= chunks[CHUNK_DATA_0].iov_len;
751 752
				vectshrink(&chunks[CHUNK_DATA_0], chunks[CHUNK_DATA_0].iov_len);
			} else {
753 754 755 756
				src = vectrpos(&chunks[CHUNK_DATA_0], num);
				vectcpy(cbuff, chunks[CHUNK_DATA_0].iov_base, num);
				vectshrink(&chunks[CHUNK_DATA_0], num);
				num = 0;
757
			}
758 759 760
			if (num >= chunks[CHUNK_DATA_1].iov_len) {
				vectcpy(cbuff, chunks[CHUNK_DATA_1].iov_base, chunks[CHUNK_DATA_1].iov_len);
				num -= chunks[CHUNK_DATA_1].iov_len;
761
				vectshrink(&chunks[CHUNK_DATA_1], chunks[CHUNK_DATA_1].iov_len);
762 763 764 765 766
			} else {
				src = vectrpos(&chunks[CHUNK_DATA_1], num);
				vectcpy(cbuff, chunks[CHUNK_DATA_1].iov_base, num);
				vectshrink(&chunks[CHUNK_DATA_1], num);
				num = 0;
767
			}
768 769 770
			if (num >= chunks[CHUNK_TRAILER].iov_len) {
				vectcpy(cbuff, chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
				num -= chunks[CHUNK_TRAILER].iov_len;
771
				vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
772 773 774 775 776
			} else {
				src = vectrpos(&chunks[CHUNK_TRAILER], num);
				vectcpy(cbuff, chunks[CHUNK_TRAILER].iov_base, num);
				vectshrink(&chunks[CHUNK_TRAILER], num);
				num = 0;
777
			}
778 779 780 781 782 783
		} else {
			/* there is not enough data to align common buffer to sector boundary, truncate common buffer */
			data_len = cbuff->iov_len % PHY_BLOCK_SIZE;
			src = vectrpos(cbuff, data_len);
			vectcpy(&chunks[CHUNK_REM], src, data_len);
			vectshrink(cbuff, data_len);
784
		}
785 786 787 788 789 790
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_0].iov_base, chunks[CHUNK_DATA_0].iov_len);
		vectshrink(&chunks[CHUNK_DATA_0], chunks[CHUNK_DATA_0].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_1].iov_base, chunks[CHUNK_DATA_1].iov_len);
		vectshrink(&chunks[CHUNK_DATA_1], chunks[CHUNK_DATA_1].iov_len);
		vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
		vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
791 792 793 794

		return;
	}

795
	/* align frame to sector size boundary; total size could have changed by the moment - recalculate */
796 797
	total_sz = get_size_from(chunks, 0, 0, INCLUDE_REM);
	len = total_sz % PHY_BLOCK_SIZE;
798 799 800 801 802 803 804 805
	dev_dbg(dev, "number of bytes crossing sector boundary: %u\n", len);
	if (len != 0) {
		if (len >= (chunks[CHUNK_DATA_1].iov_len + chunks[CHUNK_TRAILER].iov_len)) {
			/* current frame is not split or the second part of JPEG data is too short */
			data_len = len - chunks[CHUNK_DATA_1].iov_len - chunks[CHUNK_TRAILER].iov_len;
			src = vectrpos(&chunks[CHUNK_DATA_0], data_len);
			vectcpy(&chunks[CHUNK_REM], src, data_len);
			vectshrink(&chunks[CHUNK_DATA_0], data_len);
806 807 808 809
			vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_1].iov_base, chunks[CHUNK_DATA_1].iov_len);
			vectshrink(&chunks[CHUNK_DATA_1], chunks[CHUNK_DATA_1].iov_len);
			vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
			vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
		} else if (len >= chunks[CHUNK_TRAILER].iov_len) {
			/* there is enough data in second part to align the frame */
			data_len = len - chunks[CHUNK_TRAILER].iov_len;
			src = vectrpos(&chunks[CHUNK_DATA_1], data_len);
			vectcpy(&chunks[CHUNK_REM], src, data_len);
			vectshrink(&chunks[CHUNK_DATA_1], data_len);
			vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
			vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
		} else {
			/* the trailing marker is split by sector boundary, copy (PHY_BLOCK_SIZE - 1) bytes from
			 * JPEG data block(s) to remainder buffer and then add trailing marker */
			data_len = PHY_BLOCK_SIZE - (chunks[CHUNK_TRAILER].iov_len - len);
			if (data_len >= chunks[CHUNK_DATA_1].iov_len) {
				size_t cut_len = data_len - chunks[CHUNK_DATA_1].iov_len;
				src = vectrpos(&chunks[CHUNK_DATA_0], cut_len);
				vectcpy(&chunks[CHUNK_REM], src, cut_len);
				vectshrink(&chunks[CHUNK_DATA_0], cut_len);
				vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_DATA_1].iov_base, chunks[CHUNK_DATA_1].iov_len);
				vectshrink(&chunks[CHUNK_DATA_1], chunks[CHUNK_DATA_1].iov_len);
829 830
				vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
				vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
831
			} else {
832
				src = vectrpos(&chunks[CHUNK_DATA_1], data_len);
833
				vectcpy(&chunks[CHUNK_REM], src, data_len);
834 835 836 837 838
				vectshrink(&chunks[CHUNK_DATA_1], data_len);
				vectcpy(&chunks[CHUNK_REM], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
				vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
			}
		}
839 840 841
	} else {
		/* the frame is aligned to sector boundary but some buffers may be not */
		chunks[CHUNK_ALIGN].iov_base = vectrpos(cbuff, 0);
842
		chunks[CHUNK_ALIGN].iov_dma = cbuff->iov_dma + cbuff->iov_len;
843 844 845 846 847 848 849 850 851 852 853 854 855 856
		chunks[CHUNK_ALIGN].iov_len = 0;
		if (chunks[CHUNK_DATA_1].iov_len == 0) {
			data_len = chunks[CHUNK_DATA_0].iov_len % ALIGNMENT_SIZE;
			src = vectrpos(&chunks[CHUNK_DATA_0], data_len);
			vectcpy(&chunks[CHUNK_ALIGN], src, data_len);
			vectshrink(&chunks[CHUNK_DATA_0], data_len);
		} else {
			data_len = chunks[CHUNK_DATA_1].iov_len % ALIGNMENT_SIZE;
			src = vectrpos(&chunks[CHUNK_DATA_1], data_len);
			vectcpy(&chunks[CHUNK_ALIGN], src, data_len);
			vectshrink(&chunks[CHUNK_DATA_1], data_len);
		}
		vectcpy(&chunks[CHUNK_ALIGN], chunks[CHUNK_TRAILER].iov_base, chunks[CHUNK_TRAILER].iov_len);
		vectshrink(&chunks[CHUNK_TRAILER], chunks[CHUNK_TRAILER].iov_len);
857 858 859 860 861 862 863 864 865 866 867 868 869
	}

	/* debug sanity check, should not happen */
	if (cbuff->iov_len >= max_len) {
		dev_err(NULL, "ERROR: the number of bytes copied to common buffer exceeds its size\n");
	}
}

/** Calculate the number of blocks this frame will occupy. The frame must be aligned to block size */
static inline size_t get_blocks_num(struct fvec *sgl, size_t n_elem)
{
	int num;
	size_t total = 0;
870

871 872
	for (num = 0; num < n_elem; num++) {
		total += sgl[num].iov_len;
873 874
	}

875 876
	return total / PHY_BLOCK_SIZE;
}
877

878 879 880 881 882
/** Calculate the size of current frame in bytes starting from vector and offset given */
static inline size_t get_size_from(const struct fvec *vects, int index, size_t offset, int all)
{
	int i;
	size_t total = 0;
883

884 885 886
	if (index >= MAX_DATA_CHUNKS || offset > vects[index].iov_len) {
		return 0;
	}
887

888 889 890 891 892 893 894 895
	for (i = index; i < MAX_DATA_CHUNKS; i++) {
		if (i == CHUNK_REM && all == EXCLUDE_REM)
			/* remainder should not be processed */
			continue;
		if (i == index)
			total += vects[i].iov_len - offset;
		else
			total += vects[i].iov_len;
896 897
	}

898 899 900 901
	return total;
}

/** Set vectors pointing to data buffers except for JPEG data - those are set in circbuf driver */
902
static void init_vectors(struct frame_buffers *buffs, struct fvec *chunks)
903 904 905 906 907
{
	chunks[CHUNK_EXIF].iov_base = buffs->exif_buff.iov_base;
	chunks[CHUNK_EXIF].iov_len = 0;

	chunks[CHUNK_LEADER].iov_base = buffs->jpheader_buff.iov_base;
908 909
	chunks[CHUNK_LEADER].iov_len = 0;
	chunks[CHUNK_HEADER].iov_base = (unsigned char *)chunks[CHUNK_LEADER].iov_base + JPEG_MARKER_LEN;
910 911 912
	chunks[CHUNK_HEADER].iov_len = 0;

	chunks[CHUNK_TRAILER].iov_base = buffs->trailer_buff.iov_base;
913
	chunks[CHUNK_TRAILER].iov_len = 0;
914 915 916 917 918 919 920 921 922 923

	chunks[CHUNK_REM].iov_base = buffs->rem_buff.iov_base;
	chunks[CHUNK_REM].iov_len = 0;

	/* this is the only DMA mapped buffer and its DMA address should be set */
	chunks[CHUNK_COMMON].iov_base = buffs->common_buff.iov_base;
	chunks[CHUNK_COMMON].iov_dma = buffs->common_buff.iov_dma;
	chunks[CHUNK_COMMON].iov_len = 0;
}

924
/** Allocate memory for frame buffers */
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
static int init_buffers(struct device *dev, struct frame_buffers *buffs)
{
	int mult;
	int total_sz;
	unsigned char *ptr;

	buffs->exif_buff.iov_base = kmalloc(MAX_EXIF_SIZE, GFP_KERNEL);
	if (!buffs->exif_buff.iov_base)
		return -ENOMEM;
	buffs->exif_buff.iov_len = MAX_EXIF_SIZE;

	buffs->jpheader_buff.iov_base = kmalloc(JPEG_HEADER_MAXSIZE, GFP_KERNEL);
	if (!buffs->jpheader_buff.iov_base)
		goto err_header;
	buffs->jpheader_buff.iov_len = JPEG_HEADER_MAXSIZE;

	buffs->trailer_buff.iov_base = kmalloc(JPEG_MARKER_LEN, GFP_KERNEL);
	if (!buffs->trailer_buff.iov_base)
		goto err_trailer;
	buffs->trailer_buff.iov_len = JPEG_MARKER_LEN;
	ptr = buffs->trailer_buff.iov_base;
	ptr[0] = 0xff;
	ptr[1] = 0xd9;

949 950 951
	/* common buffer should be large enough to contain JPEG header, Exif, some alignment bytes and
	 * remainder from previous frame */
	total_sz = MAX_EXIF_SIZE + JPEG_HEADER_MAXSIZE + ALIGNMENT_SIZE + 2 * PHY_BLOCK_SIZE;
952 953 954 955 956
	if (total_sz > PAGE_SIZE) {
		mult = total_sz / PAGE_SIZE + 1;
		total_sz = mult * PAGE_SIZE;
	} else {
		total_sz = PAGE_SIZE;
957
	}
958 959 960 961 962 963 964 965 966
	buffs->common_buff.iov_base = kmalloc(total_sz, GFP_KERNEL);
	if (!buffs->common_buff.iov_base)
		goto err_common;
	buffs->common_buff.iov_len = total_sz;
	/* this is the only buffer which needs DMA mapping as all other data will be collected in it */
	buffs->common_buff.iov_dma = dma_map_single(dev, buffs->common_buff.iov_base, buffs->common_buff.iov_len, DMA_TO_DEVICE);
	if (dma_mapping_error(dev, buffs->common_buff.iov_dma))
		goto err_common_dma;

967
	buffs->rem_buff.iov_base = kmalloc(2 * PHY_BLOCK_SIZE, GFP_KERNEL);
968 969
	if (!buffs->rem_buff.iov_base)
		goto err_remainder;
970
	buffs->rem_buff.iov_len = 2 * PHY_BLOCK_SIZE;
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

	return 0;

err_remainder:
	dma_unmap_single(dev, buffs->common_buff.iov_dma, buffs->common_buff.iov_len, DMA_TO_DEVICE);
err_common_dma:
	kfree(buffs->common_buff.iov_base);
err_common:
	kfree(buffs->trailer_buff.iov_base);
err_trailer:
	kfree(buffs->jpheader_buff.iov_base);
err_header:
	kfree(buffs->exif_buff.iov_base);
	return -ENOMEM;
}

987
/** Free allocated frame buffers */
988 989 990 991 992 993 994 995 996
static void deinit_buffers(struct device *dev, struct frame_buffers *buffs)
{
	kfree(buffs->jpheader_buff.iov_base);
	kfree(buffs->exif_buff.iov_base);
	kfree(buffs->trailer_buff.iov_base);
	dma_unmap_single(dev, buffs->common_buff.iov_dma, buffs->common_buff.iov_len, DMA_TO_DEVICE);
	kfree(buffs->common_buff.iov_base);
	kfree(buffs->rem_buff.iov_base);
}
997

998
/** Discard buffer pointers which makes the command slot marked as empty */
999 1000 1001
static inline void reset_chunks(struct fvec *vects, int all)
{
	int i;
1002

1003 1004 1005 1006 1007 1008
	for (i = 0; i < MAX_DATA_CHUNKS; i++) {
		if (i != CHUNK_REM)
			vects[i].iov_len = 0;
	}
	if (all) {
		vects[CHUNK_REM].iov_len = 0;
1009
	}
1010
}
1011

1012
/** Get driver private structure from pointer to device structure */
1013 1014 1015 1016 1017 1018 1019 1020
static inline struct elphel_ahci_priv *dev_get_dpriv(struct device *dev)
{
	struct ata_host *host = dev_get_drvdata(dev);
	struct ahci_host_priv *hpriv = host->private_data;
	struct elphel_ahci_priv *dpriv = hpriv->plat_data;

	return dpriv;
}
1021

1022
/** Process command and return the number of S/G entries mapped */
1023
static int process_cmd(struct elphel_ahci_priv *dpriv)
1024
{
1025
	struct fvec *cbuff;
1026 1027
	struct ata_host *host = dev_get_drvdata(dpriv->dev);
	struct ata_port *port = host->ports[DEFAULT_PORT_NUM];
1028
	size_t max_sz = (MAX_LBA_COUNT + 1) * PHY_BLOCK_SIZE;
1029
	size_t rem_sz = get_size_from(dpriv->data_chunks[dpriv->head_ptr], dpriv->curr_data_chunk, dpriv->curr_data_offset, EXCLUDE_REM);
1030

1031 1032 1033 1034
	if (dpriv->flags & PROC_CMD)
		dpriv->lba_ptr.lba_write += dpriv->lba_ptr.wr_count;
	dpriv->flags |= PROC_CMD;

1035 1036 1037 1038 1039 1040 1041
	/* define ATA command to use for current transaction */
	if ((dpriv->lba_ptr.lba_write & ~ADDR_MASK_28_BIT) || rem_sz > max_sz) {
		dpriv->curr_cmd = ATA_CMD_WRITE_EXT;
		dpriv->max_data_sz = (MAX_LBA_COUNT_EXT + 1) * PHY_BLOCK_SIZE;
	} else {
		dpriv->curr_cmd = ATA_CMD_WRITE;
		dpriv->max_data_sz = (MAX_LBA_COUNT + 1) * PHY_BLOCK_SIZE;
1042 1043
	}

1044 1045
	dpriv->sg_elems = map_vectors(dpriv);
	if (dpriv->sg_elems != 0) {
1046
		dump_sg_list(dpriv->dev, dpriv->sgl, dpriv->sg_elems);
1047 1048
		get_fpga_rtc(&dpriv->stat.start_time);
		set_timer(dpriv);
1049 1050

		dpriv->lba_ptr.wr_count = get_blocks_num(dpriv->sgl, dpriv->sg_elems);
1051 1052 1053 1054
		if (dpriv->lba_ptr.lba_write + dpriv->lba_ptr.wr_count > dpriv->lba_ptr.lba_end) {
			/* the frame rolls over the buffer boundary, don't split it and start writing from the beginning */
			dpriv->lba_ptr.lba_write = dpriv->lba_ptr.lba_start;
		}
1055
		cbuff = &dpriv->fbuffs[dpriv->head_ptr].common_buff;
1056
		dma_sync_single_for_device(dpriv->dev, cbuff->iov_dma, cbuff->iov_len, DMA_TO_DEVICE);
1057
		elphel_cmd_issue(port, dpriv->lba_ptr.lba_write, dpriv->lba_ptr.wr_count, dpriv->sgl, dpriv->sg_elems, dpriv->curr_cmd);
1058
	}
1059 1060 1061
	return dpriv->sg_elems;
}

1062
/** Finish currently running command */
1063
static void finish_cmd(struct elphel_ahci_priv *dpriv)
1064 1065 1066
{
	int all;

1067
	remove_timer(dpriv);
1068 1069 1070 1071 1072 1073 1074
	dpriv->lba_ptr.wr_count = 0;
	if ((dpriv->flags & LAST_BLOCK) == 0) {
		all = 0;
	} else {
		all = 1;
		dpriv->flags &= ~LAST_BLOCK;
	}
1075
	reset_chunks(dpriv->data_chunks[dpriv->head_ptr], all);
1076 1077 1078 1079
	dpriv->curr_cmd = 0;
	dpriv->max_data_sz = 0;
	dpriv->curr_data_chunk = 0;
	dpriv->curr_data_offset = 0;
1080
	dpriv->flags &= ~PROC_CMD;
1081 1082
}

1083
/** Fill free space in REM buffer with 0 and save the remaining data chunk */
1084
static void finish_rec(struct elphel_ahci_priv *dpriv)
1085 1086
{
	size_t stuff_len;
1087
	unsigned char *src;
1088 1089
	struct fvec *cvect = &dpriv->data_chunks[dpriv->head_ptr][CHUNK_COMMON];
	struct fvec *rvect = &dpriv->data_chunks[dpriv->head_ptr][CHUNK_REM];
1090

1091
	if (rvect->iov_len == 0)
1092 1093
		return;

1094
	dev_dbg(dpriv->dev, "write last chunk of data from slot %u, size: %u\n", dpriv->head_ptr, rvect->iov_len);
1095
	stuff_len = PHY_BLOCK_SIZE - rvect->iov_len;
1096 1097
	src = vectrpos(rvect, 0);
	memset(src, 0, stuff_len);
1098
	rvect->iov_len += stuff_len;
1099
	dma_sync_single_for_cpu(dpriv->dev, dpriv->fbuffs[dpriv->head_ptr].common_buff.iov_dma, dpriv->fbuffs[dpriv->head_ptr].common_buff.iov_len, DMA_TO_DEVICE);
1100 1101
	vectcpy(cvect, rvect->iov_base, rvect->iov_len);
	vectshrink(rvect, rvect->iov_len);
1102 1103

	dpriv->flags |= LAST_BLOCK;
1104
	process_cmd(dpriv);
1105 1106
}

1107 1108
/** Move a pointer to free command slot one step forward. This function holds spin lock #elphel_ahci_priv::flags_lock */
static int move_tail(struct elphel_ahci_priv *dpriv)
1109
{
1110
	size_t slot = (dpriv->tail_ptr + 1) % MAX_CMD_SLOTS;
1111

1112
	if (slot != dpriv->head_ptr) {
1113
		set_flag(dpriv, LOCK_TAIL);
1114
		dpriv->tail_ptr = slot;
1115
		dev_dbg(dpriv->dev, "move tail pointer to slot: %u\n", slot);
1116 1117 1118 1119 1120 1121 1122
		return 0;
	} else {
		/* no more free command slots */
		return -1;
	}
}

1123 1124
/** Move a pointer to next ready command. This function holds spin lock #elphel_ahci_priv::flags_lock*/
static int move_head(struct elphel_ahci_priv *dpriv)
1125 1126
{
	size_t use_tail;
1127
	unsigned long irq_flags;
1128 1129
	size_t slot = (dpriv->head_ptr + 1) % MAX_CMD_SLOTS;

1130
	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
1131 1132 1133 1134 1135 1136
	if (dpriv->flags & LOCK_TAIL) {
		/* current command slot is not ready yet, use previous */
		use_tail = get_prev_slot(dpriv);
	} else {
		use_tail = dpriv->tail_ptr;
	}
1137
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
1138 1139 1140

	if (dpriv->head_ptr != use_tail) {
		dpriv->head_ptr = slot;
1141
		dev_dbg(dpriv->dev, "move head pointer to slot: %u\n", slot);
1142 1143 1144 1145
		return 0;
	} else {
		/* no more commands in queue */
		return -1;
1146 1147 1148
	}

}
1149

1150
/** Check if command queue is empty */
1151
static int is_cmdq_empty(const struct elphel_ahci_priv *dpriv)
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
{
	size_t use_tail;

	if (dpriv->flags & LOCK_TAIL) {
		/* current command slot is not ready yet, use previous */
		use_tail = get_prev_slot(dpriv);
	} else {
		use_tail = dpriv->tail_ptr;
	}
	if (dpriv->head_ptr != use_tail)
		return 0;
	else
		return 1;
}

1167
/** Get command slot before the last one filled in */
1168
static size_t get_prev_slot(const struct elphel_ahci_priv *dpriv)
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
{
	size_t slot;

	if (dpriv->tail_ptr == dpriv->head_ptr)
		return dpriv->tail_ptr;

	if (dpriv->tail_ptr != 0) {
		slot = dpriv->tail_ptr - 1;
	} else {
		slot = MAX_CMD_SLOTS - 1;
	}
	return slot;
}

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
void error_handler(struct elphel_ahci_priv *dpriv)
{
	struct ata_host *host = dev_get_drvdata(dpriv->dev);
	struct ahci_host_priv *hpriv = host->private_data;
	struct ata_port *ap = host->ports[DEFAULT_PORT_NUM];
	struct ata_link *link = &ap->link;

	int pmp = link->pmp;
	int rc;
	unsigned int class;
	unsigned long deadline = jiffies + msecs_to_jiffies(DEFAULT_CMD_TIMEOUT);

	dump_iomem(hpriv->mmio);
	dump_dpriv_fields(dpriv);
	dump_sg_list_uncond(dpriv->sgl, dpriv->sg_elems);
	printk(KERN_DEBUG "reset command queue and all flags\n");
	reset_all_commands(dpriv);


	/* the following commented code was used to try recovery after IO error */
//	printk(KERN_DEBUG "Trying hard reset the link\n");
//	rc = ap->ops->hardreset(link, &class, deadline);
//	if (rc != 0)
//		printk(KERN_DEBUG "error: ahci_hardreset returned %i\n", rc);
//	else
//		printk(KERN_DEBUG "hard reset OK, waiting for error handler to complete\n");
//
//	ata_port_wait_eh(ap);
//	printk(KERN_DEBUG "OK, going back to commands execution\n");
}

1214 1215 1216 1217 1218
/** Get and enqueue new command */
static ssize_t rawdev_write(struct device *dev,  ///< device structure associated with the driver
		struct device_attribute *attr,           ///< interface for device attributes
		const char *buff,                        ///< buffer containing new command
		size_t buff_sz)                          ///< the size of the command buffer
1219
{
1220
	ssize_t rcvd = 0;
1221
	bool proceed = false;
1222
	bool start_eh = false;
1223
	unsigned long irq_flags;
1224 1225
	struct elphel_ahci_priv *dpriv = dev_get_dpriv(dev);
	struct frame_data fdata;
1226 1227
	struct frame_buffers *buffs;
	struct fvec *chunks;
1228

1229
	/* simple check if we've got the right command */
1230
	if (buff_sz != sizeof(struct frame_data)) {
1231
		dev_err(dev, "the size of the data buffer is incorrect, should be equal to sizeof(struct frame_data)\n");
1232 1233 1234
		return -EINVAL;
	}
	memcpy(&fdata, buff, sizeof(struct frame_data));
1235

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	/* error recovery, do not continue recording and wait for full camera reset */
	if (dpriv->io_error_flag) {
		printk_once(KERN_CRIT "IO error detected, recording stopped and waiting for reboot\n");
		return -EIO;
	}
	/* check if we should reset controller */
	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
	if (dpriv->flags & START_EH) {
		start_eh = true;
	}
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
	if (start_eh) {
		dpriv->io_error_flag = 1;
		error_handler(dpriv);
		return -EIO;
	}

1253
	/* lock disk resource as soon as possible */
1254
	spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
1255 1256 1257
	if ((dpriv->flags & DISK_BUSY) == 0) {
		dpriv->flags |= DISK_BUSY;
		proceed = true;
1258 1259 1260
	}
	spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);

1261
	if (fdata.cmd & DRV_CMD_FINISH) {
1262 1263
		if ((dpriv->flags & PROC_CMD) == 0 && proceed) {
			finish_rec(dpriv);
1264 1265 1266
		} else {
			dpriv->flags |= DELAYED_FINISH;
		}
1267 1268
		return buff_sz;
	}
1269

1270
	if (move_tail(dpriv) == -1) {
1271
		/* we are not ready yet because command queue is full */
1272
		printk_ratelimited(KERN_DEBUG "command queue is full, flags = %u, proceed = %d\n", dpriv->flags, proceed);
1273 1274
		return -EAGAIN;
	}
1275
	chunks = dpriv->data_chunks[dpriv->tail_ptr];
1276
	buffs = &dpriv->fbuffs[dpriv->tail_ptr];
1277

1278
	dev_dbg(dev, "process frame from sensor port: %u, command = %d, flags = %u\n", fdata.sensor_port, fdata.cmd, dpriv->flags);
1279 1280 1281 1282
	if (fdata.cmd & DRV_CMD_EXIF) {
		rcvd = exif_get_data(fdata.sensor_port, fdata.meta_index, buffs->exif_buff.iov_base, buffs->exif_buff.iov_len);
		chunks[CHUNK_EXIF].iov_len = rcvd;
	}
1283

1284
	rcvd = jpeghead_get_data(fdata.sensor_port, buffs->jpheader_buff.iov_base, buffs->jpheader_buff.iov_len, 0);
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
	if (rcvd < 0) {
		/* free resource lock and current command slot */
		if (proceed) {
			spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
			dpriv->flags &= ~DISK_BUSY;
			spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
		}
		reset_chunks(chunks, 0);
		dpriv->tail_ptr = get_prev_slot(dpriv);
		dpriv->flags &= ~LOCK_TAIL;
		dev_err(dev, "could not get JPEG header, error %d\n", rcvd);
		return -EINVAL;
	}
1298 1299 1300
	chunks[CHUNK_LEADER].iov_len = JPEG_MARKER_LEN;
	chunks[CHUNK_TRAILER].iov_len = JPEG_MARKER_LEN;
	chunks[CHUNK_HEADER].iov_len = rcvd - chunks[CHUNK_LEADER].iov_len;
1301

1302
	rcvd = circbuf_get_ptr(fdata.sensor_port, fdata.cirbuf_ptr, fdata.jpeg_len, &chunks[CHUNK_DATA_0], &chunks[CHUNK_DATA_1]);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	if (rcvd < 0) {
		/* free resource lock and current command slot */
		if (proceed) {
			spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
			dpriv->flags &= ~DISK_BUSY;
			spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
		}
		reset_chunks(chunks, 0);
		dpriv->tail_ptr = get_prev_slot(dpriv);
		dpriv->flags &= ~LOCK_TAIL;
		dev_err(dev, "could not get JPEG data, error %d\n", rcvd);
		return -EINVAL;
	}
1316
	align_frame(dpriv);
1317
	/* new command slot is ready now and can be unlocked */
1318
	reset_flag(dpriv, LOCK_TAIL);
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
	if (!proceed) {
		/* disk may be free by the moment, try to grab it */
		spin_lock_irqsave(&dpriv->flags_lock, irq_flags);
		if ((dpriv->flags & DISK_BUSY) == 0) {
			dpriv->flags |= DISK_BUSY;
			proceed = true;
		}
		spin_unlock_irqrestore(&dpriv->flags_lock, irq_flags);
	}
	if ((dpriv->flags & PROC_CMD) == 0 && proceed) {
1330
		if (get_size_from(dpriv->data_chunks[dpriv->head_ptr], 0, 0, EXCLUDE_REM) == 0)
1331
			move_head(dpriv);
1332
		process_cmd(dpriv);
1333
	}
1334 1335 1336 1337 1338 1339 1340

	return buff_sz;
}

/** Prepare software constructed command FIS in command table area. The structure of the
 * command FIS is described in Transport Layer chapter of Serial ATA revision 3.1 documentation.
 */
1341 1342 1343 1344
static inline void prep_cfis(uint8_t *cmd_tbl,   ///< pointer to the beginning of command table
		uint8_t cmd,                             ///< ATA command as described in ATA/ATAPI command set
		uint64_t start_addr,                     ///< LBA start address
		uint16_t count)                          ///< sector count, the number of 512 byte sectors to read or write
1345
		                                         ///< @return None
1346
{
1347
	uint8_t device, ctrl;
1348 1349 1350 1351 1352

	/* select the content of Device and Control registers based on command, read the description of
	 * a command in ATA/ATAPI command set documentation
	 */
	switch (cmd) {
1353
	case ATA_CMD_WRITE:
1354 1355 1356 1357 1358 1359 1360 1361
	case ATA_CMD_READ:
		device = 0xe0 | ((start_addr >> 24) & 0x0f);
		ctrl = 0x08;
		/* this is 28-bit command; 4 bits of the address have already been
		 * placed to Device register, invalidate the remaining (if any) upper
		 * bits of the address and leave only 24 significant bits (just in case)
		 */
		start_addr &= 0xffffff;
1362
		count &= 0xff;
1363
		break;
1364
	case ATA_CMD_WRITE_EXT:
1365 1366 1367 1368 1369
	case ATA_CMD_READ_EXT:
		device = 0xe0;
		ctrl = 0x08;
		break;
	default:
1370 1371
		device = 0xe0;
		ctrl = 0x08;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
	}

	cmd_tbl[0] = 0x27;                       // H2D register FIS
	cmd_tbl[1] = 0x80;                       // set C = 1
	cmd_tbl[2] = cmd;                        // ATA READ or WRITE DMA command as described in ATA/ATAPI command set
	cmd_tbl[3] = 0;                          // features(7:0)
	cmd_tbl[4] = start_addr & 0xff;          // LBA(7:0)
	cmd_tbl[5] = (start_addr >> 8)  & 0xff;  // LBA(15:8)
	cmd_tbl[6] = (start_addr >> 16) & 0xff;  // LBA(23:16)
	cmd_tbl[7] = device;                     // device
	cmd_tbl[8] = (start_addr >> 24)  & 0xff; // LBA(31:24)
	cmd_tbl[9] = (start_addr >> 32)  & 0xff; // LBA(39:32)
	cmd_tbl[10] = (start_addr >> 40) & 0xff; // LBA(47:40)
	cmd_tbl[11] = 0;                         // features(15:8)
	cmd_tbl[12] = count & 0xff;              // count(7:0)
	cmd_tbl[13] = (count >> 8) & 0xff;       // count(15:8)
	cmd_tbl[14] = 0;                         // ICC (isochronous command completion)
	cmd_tbl[15] = ctrl;                      // control
}

1392
/** Map S/G list to physical region descriptor table in AHCI controller command table */
1393
static inline void prep_prdt(struct fvec *sgl,   ///< pointer to S/G list which should be mapped to physical
1394 1395 1396 1397 1398 1399 1400
		                                         ///< region description table
		unsigned int n_elem,                     ///< the number of elements in @e sgl
		struct ahci_sg *ahci_sgl)                ///< pointer to physical region description table
		                                         ///< @return None
{
	unsigned int num = 0;

1401 1402 1403 1404
	for (num = 0; num < n_elem; num++) {
		ahci_sgl[num].addr = cpu_to_le32(sgl[num].iov_dma & 0xffffffff);
		ahci_sgl[num].addr_hi = cpu_to_le32((sgl[num].iov_dma >> 16) >> 16);
		ahci_sgl[num].flags_size = cpu_to_le32(sgl[num].iov_len - 1);
1405 1406 1407
	}
}

1408 1409 1410 1411
/** Prepare and issue read or write command */
static void elphel_cmd_issue(struct ata_port *ap,///< device port for which the command should be issued
		uint64_t start,                          ///< LBA start address
		uint16_t count,                          ///< the number of sectors to read or write
1412
		struct fvec *sgl,                        ///< S/G list pointing to data buffers
1413 1414 1415 1416
		unsigned int elem,                       ///< the number of elements in @e sgl
		uint8_t cmd)                             ///< the command to be issued; should be ATA_CMD_READ, ATA_CMD_READ_EXT,
		                                         ///< ATA_CMD_WRITE or ATA_CMD_WRITE_EXT, other commands are not tested
		                                         ///< @return None
1417
{
1418 1419
	uint32_t opts;
	uint8_t *cmd_tbl;
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	unsigned int slot_num = 0;
	struct ahci_port_priv *pp = ap->private_data;
	struct ahci_host_priv *hpriv = ap->host->private_data;
	struct elphel_ahci_priv *dpriv = hpriv->plat_data;
	struct ahci_sg *ahci_sg;
	void __iomem *port_mmio = ahci_port_base(ap);

	dpriv->flags |= IRQ_SIMPLE;

	/* prepare command FIS */
	dma_sync_single_for_cpu(ap->dev, pp->cmd_tbl_dma, AHCI_CMD_TBL_AR_SZ, DMA_TO_DEVICE);
	cmd_tbl = pp->cmd_tbl + slot_num * AHCI_CMD_TBL_SZ;
1432
	prep_cfis(cmd_tbl, cmd, start, count);
1433 1434 1435

	/* prepare physical region descriptor table */
	ahci_sg = pp->cmd_tbl + slot_num * AHCI_CMD_TBL_SZ + AHCI_CMD_TBL_HDR_SZ;
1436
	prep_prdt(sgl, elem, ahci_sg);
1437 1438

	/* prepare command header */
1439 1440 1441
	opts = CMD_FIS_LEN | (elem << 16) | AHCI_CMD_PREFETCH | AHCI_CMD_CLR_BUSY;
	if (cmd == ATA_CMD_WRITE || cmd == ATA_CMD_WRITE_EXT)
		opts |= AHCI_CMD_WRITE;
1442
	ahci_fill_cmd_slot(pp, slot_num, opts);
1443

1444 1445
	dev_dbg(ap->dev, "dump command table content, first %d bytes, phys addr = 0x%x:\n", 16, pp->cmd_tbl_dma);
	print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, pp->cmd_tbl, 16);
1446

1447 1448 1449
	dma_sync_single_for_device(ap->dev, pp->cmd_tbl_dma, AHCI_CMD_TBL_AR_SZ, DMA_TO_DEVICE);

	/* issue command */
1450
	writel(0x11, port_mmio + PORT_CMD);
</