xref: /openbmc/u-boot/drivers/ddr/altera/sequencer.c (revision 3cd0906cc21bc88bfe318b32a08c5fd8d8915b7f)
1 /*
2  * Copyright Altera Corporation (C) 2012-2015
3  *
4  * SPDX-License-Identifier:    BSD-3-Clause
5  */
6 
7 #include <common.h>
8 #include <asm/io.h>
9 #include <asm/arch/sdram.h>
10 #include <errno.h>
11 #include "sequencer.h"
12 
13 /*
14  * FIXME: This path is temporary until the SDRAM driver gets
15  *        a proper thorough cleanup.
16  */
17 #include "../../../board/altera/socfpga/qts/sequencer_auto.h"
18 #include "../../../board/altera/socfpga/qts/sequencer_defines.h"
19 
20 static struct socfpga_sdr_rw_load_manager *sdr_rw_load_mgr_regs =
21 	(struct socfpga_sdr_rw_load_manager *)(SDR_PHYGRP_RWMGRGRP_ADDRESS | 0x800);
22 
23 static struct socfpga_sdr_rw_load_jump_manager *sdr_rw_load_jump_mgr_regs =
24 	(struct socfpga_sdr_rw_load_jump_manager *)(SDR_PHYGRP_RWMGRGRP_ADDRESS | 0xC00);
25 
26 static struct socfpga_sdr_reg_file *sdr_reg_file =
27 	(struct socfpga_sdr_reg_file *)SDR_PHYGRP_REGFILEGRP_ADDRESS;
28 
29 static struct socfpga_sdr_scc_mgr *sdr_scc_mgr =
30 	(struct socfpga_sdr_scc_mgr *)(SDR_PHYGRP_SCCGRP_ADDRESS | 0xe00);
31 
32 static struct socfpga_phy_mgr_cmd *phy_mgr_cmd =
33 	(struct socfpga_phy_mgr_cmd *)SDR_PHYGRP_PHYMGRGRP_ADDRESS;
34 
35 static struct socfpga_phy_mgr_cfg *phy_mgr_cfg =
36 	(struct socfpga_phy_mgr_cfg *)(SDR_PHYGRP_PHYMGRGRP_ADDRESS | 0x40);
37 
38 static struct socfpga_data_mgr *data_mgr =
39 	(struct socfpga_data_mgr *)SDR_PHYGRP_DATAMGRGRP_ADDRESS;
40 
41 static struct socfpga_sdr_ctrl *sdr_ctrl =
42 	(struct socfpga_sdr_ctrl *)SDR_CTRLGRP_ADDRESS;
43 
44 const struct socfpga_sdram_rw_mgr_config *rwcfg;
45 const struct socfpga_sdram_io_config *iocfg;
46 const struct socfpga_sdram_misc_config *misccfg;
47 
48 #define DELTA_D		1
49 
50 /*
51  * In order to reduce ROM size, most of the selectable calibration steps are
52  * decided at compile time based on the user's calibration mode selection,
53  * as captured by the STATIC_CALIB_STEPS selection below.
54  *
55  * However, to support simulation-time selection of fast simulation mode, where
56  * we skip everything except the bare minimum, we need a few of the steps to
57  * be dynamic.  In those cases, we either use the DYNAMIC_CALIB_STEPS for the
58  * check, which is based on the rtl-supplied value, or we dynamically compute
59  * the value to use based on the dynamically-chosen calibration mode
60  */
61 
62 #define DLEVEL 0
63 #define STATIC_IN_RTL_SIM 0
64 #define STATIC_SKIP_DELAY_LOOPS 0
65 
66 #define STATIC_CALIB_STEPS (STATIC_IN_RTL_SIM | CALIB_SKIP_FULL_TEST | \
67 	STATIC_SKIP_DELAY_LOOPS)
68 
69 /* calibration steps requested by the rtl */
70 uint16_t dyn_calib_steps;
71 
72 /*
73  * To make CALIB_SKIP_DELAY_LOOPS a dynamic conditional option
74  * instead of static, we use boolean logic to select between
75  * non-skip and skip values
76  *
77  * The mask is set to include all bits when not-skipping, but is
78  * zero when skipping
79  */
80 
81 uint16_t skip_delay_mask;	/* mask off bits when skipping/not-skipping */
82 
83 #define SKIP_DELAY_LOOP_VALUE_OR_ZERO(non_skip_value) \
84 	((non_skip_value) & skip_delay_mask)
85 
86 struct gbl_type *gbl;
87 struct param_type *param;
88 
89 static void set_failing_group_stage(uint32_t group, uint32_t stage,
90 	uint32_t substage)
91 {
92 	/*
93 	 * Only set the global stage if there was not been any other
94 	 * failing group
95 	 */
96 	if (gbl->error_stage == CAL_STAGE_NIL)	{
97 		gbl->error_substage = substage;
98 		gbl->error_stage = stage;
99 		gbl->error_group = group;
100 	}
101 }
102 
103 static void reg_file_set_group(u16 set_group)
104 {
105 	clrsetbits_le32(&sdr_reg_file->cur_stage, 0xffff0000, set_group << 16);
106 }
107 
108 static void reg_file_set_stage(u8 set_stage)
109 {
110 	clrsetbits_le32(&sdr_reg_file->cur_stage, 0xffff, set_stage & 0xff);
111 }
112 
113 static void reg_file_set_sub_stage(u8 set_sub_stage)
114 {
115 	set_sub_stage &= 0xff;
116 	clrsetbits_le32(&sdr_reg_file->cur_stage, 0xff00, set_sub_stage << 8);
117 }
118 
119 /**
120  * phy_mgr_initialize() - Initialize PHY Manager
121  *
122  * Initialize PHY Manager.
123  */
124 static void phy_mgr_initialize(void)
125 {
126 	u32 ratio;
127 
128 	debug("%s:%d\n", __func__, __LINE__);
129 	/* Calibration has control over path to memory */
130 	/*
131 	 * In Hard PHY this is a 2-bit control:
132 	 * 0: AFI Mux Select
133 	 * 1: DDIO Mux Select
134 	 */
135 	writel(0x3, &phy_mgr_cfg->mux_sel);
136 
137 	/* USER memory clock is not stable we begin initialization  */
138 	writel(0, &phy_mgr_cfg->reset_mem_stbl);
139 
140 	/* USER calibration status all set to zero */
141 	writel(0, &phy_mgr_cfg->cal_status);
142 
143 	writel(0, &phy_mgr_cfg->cal_debug_info);
144 
145 	/* Init params only if we do NOT skip calibration. */
146 	if ((dyn_calib_steps & CALIB_SKIP_ALL) == CALIB_SKIP_ALL)
147 		return;
148 
149 	ratio = rwcfg->mem_dq_per_read_dqs /
150 		rwcfg->mem_virtual_groups_per_read_dqs;
151 	param->read_correct_mask_vg = (1 << ratio) - 1;
152 	param->write_correct_mask_vg = (1 << ratio) - 1;
153 	param->read_correct_mask = (1 << rwcfg->mem_dq_per_read_dqs) - 1;
154 	param->write_correct_mask = (1 << rwcfg->mem_dq_per_write_dqs) - 1;
155 }
156 
157 /**
158  * set_rank_and_odt_mask() - Set Rank and ODT mask
159  * @rank:	Rank mask
160  * @odt_mode:	ODT mode, OFF or READ_WRITE
161  *
162  * Set Rank and ODT mask (On-Die Termination).
163  */
164 static void set_rank_and_odt_mask(const u32 rank, const u32 odt_mode)
165 {
166 	u32 odt_mask_0 = 0;
167 	u32 odt_mask_1 = 0;
168 	u32 cs_and_odt_mask;
169 
170 	if (odt_mode == RW_MGR_ODT_MODE_OFF) {
171 		odt_mask_0 = 0x0;
172 		odt_mask_1 = 0x0;
173 	} else {	/* RW_MGR_ODT_MODE_READ_WRITE */
174 		switch (rwcfg->mem_number_of_ranks) {
175 		case 1:	/* 1 Rank */
176 			/* Read: ODT = 0 ; Write: ODT = 1 */
177 			odt_mask_0 = 0x0;
178 			odt_mask_1 = 0x1;
179 			break;
180 		case 2:	/* 2 Ranks */
181 			if (rwcfg->mem_number_of_cs_per_dimm == 1) {
182 				/*
183 				 * - Dual-Slot , Single-Rank (1 CS per DIMM)
184 				 *   OR
185 				 * - RDIMM, 4 total CS (2 CS per DIMM, 2 DIMM)
186 				 *
187 				 * Since MEM_NUMBER_OF_RANKS is 2, they
188 				 * are both single rank with 2 CS each
189 				 * (special for RDIMM).
190 				 *
191 				 * Read: Turn on ODT on the opposite rank
192 				 * Write: Turn on ODT on all ranks
193 				 */
194 				odt_mask_0 = 0x3 & ~(1 << rank);
195 				odt_mask_1 = 0x3;
196 			} else {
197 				/*
198 				 * - Single-Slot , Dual-Rank (2 CS per DIMM)
199 				 *
200 				 * Read: Turn on ODT off on all ranks
201 				 * Write: Turn on ODT on active rank
202 				 */
203 				odt_mask_0 = 0x0;
204 				odt_mask_1 = 0x3 & (1 << rank);
205 			}
206 			break;
207 		case 4:	/* 4 Ranks */
208 			/* Read:
209 			 * ----------+-----------------------+
210 			 *           |         ODT           |
211 			 * Read From +-----------------------+
212 			 *   Rank    |  3  |  2  |  1  |  0  |
213 			 * ----------+-----+-----+-----+-----+
214 			 *     0     |  0  |  1  |  0  |  0  |
215 			 *     1     |  1  |  0  |  0  |  0  |
216 			 *     2     |  0  |  0  |  0  |  1  |
217 			 *     3     |  0  |  0  |  1  |  0  |
218 			 * ----------+-----+-----+-----+-----+
219 			 *
220 			 * Write:
221 			 * ----------+-----------------------+
222 			 *           |         ODT           |
223 			 * Write To  +-----------------------+
224 			 *   Rank    |  3  |  2  |  1  |  0  |
225 			 * ----------+-----+-----+-----+-----+
226 			 *     0     |  0  |  1  |  0  |  1  |
227 			 *     1     |  1  |  0  |  1  |  0  |
228 			 *     2     |  0  |  1  |  0  |  1  |
229 			 *     3     |  1  |  0  |  1  |  0  |
230 			 * ----------+-----+-----+-----+-----+
231 			 */
232 			switch (rank) {
233 			case 0:
234 				odt_mask_0 = 0x4;
235 				odt_mask_1 = 0x5;
236 				break;
237 			case 1:
238 				odt_mask_0 = 0x8;
239 				odt_mask_1 = 0xA;
240 				break;
241 			case 2:
242 				odt_mask_0 = 0x1;
243 				odt_mask_1 = 0x5;
244 				break;
245 			case 3:
246 				odt_mask_0 = 0x2;
247 				odt_mask_1 = 0xA;
248 				break;
249 			}
250 			break;
251 		}
252 	}
253 
254 	cs_and_odt_mask = (0xFF & ~(1 << rank)) |
255 			  ((0xFF & odt_mask_0) << 8) |
256 			  ((0xFF & odt_mask_1) << 16);
257 	writel(cs_and_odt_mask, SDR_PHYGRP_RWMGRGRP_ADDRESS |
258 				RW_MGR_SET_CS_AND_ODT_MASK_OFFSET);
259 }
260 
261 /**
262  * scc_mgr_set() - Set SCC Manager register
263  * @off:	Base offset in SCC Manager space
264  * @grp:	Read/Write group
265  * @val:	Value to be set
266  *
267  * This function sets the SCC Manager (Scan Chain Control Manager) register.
268  */
269 static void scc_mgr_set(u32 off, u32 grp, u32 val)
270 {
271 	writel(val, SDR_PHYGRP_SCCGRP_ADDRESS | off | (grp << 2));
272 }
273 
274 /**
275  * scc_mgr_initialize() - Initialize SCC Manager registers
276  *
277  * Initialize SCC Manager registers.
278  */
279 static void scc_mgr_initialize(void)
280 {
281 	/*
282 	 * Clear register file for HPS. 16 (2^4) is the size of the
283 	 * full register file in the scc mgr:
284 	 *	RFILE_DEPTH = 1 + log2(MEM_DQ_PER_DQS + 1 + MEM_DM_PER_DQS +
285 	 *                             MEM_IF_READ_DQS_WIDTH - 1);
286 	 */
287 	int i;
288 
289 	for (i = 0; i < 16; i++) {
290 		debug_cond(DLEVEL == 1, "%s:%d: Clearing SCC RFILE index %u\n",
291 			   __func__, __LINE__, i);
292 		scc_mgr_set(SCC_MGR_HHP_RFILE_OFFSET, 0, i);
293 	}
294 }
295 
296 static void scc_mgr_set_dqdqs_output_phase(uint32_t write_group, uint32_t phase)
297 {
298 	scc_mgr_set(SCC_MGR_DQDQS_OUT_PHASE_OFFSET, write_group, phase);
299 }
300 
301 static void scc_mgr_set_dqs_bus_in_delay(uint32_t read_group, uint32_t delay)
302 {
303 	scc_mgr_set(SCC_MGR_DQS_IN_DELAY_OFFSET, read_group, delay);
304 }
305 
306 static void scc_mgr_set_dqs_en_phase(uint32_t read_group, uint32_t phase)
307 {
308 	scc_mgr_set(SCC_MGR_DQS_EN_PHASE_OFFSET, read_group, phase);
309 }
310 
311 static void scc_mgr_set_dqs_en_delay(uint32_t read_group, uint32_t delay)
312 {
313 	scc_mgr_set(SCC_MGR_DQS_EN_DELAY_OFFSET, read_group, delay);
314 }
315 
316 static void scc_mgr_set_dqs_io_in_delay(uint32_t delay)
317 {
318 	scc_mgr_set(SCC_MGR_IO_IN_DELAY_OFFSET, rwcfg->mem_dq_per_write_dqs,
319 		    delay);
320 }
321 
322 static void scc_mgr_set_dq_in_delay(uint32_t dq_in_group, uint32_t delay)
323 {
324 	scc_mgr_set(SCC_MGR_IO_IN_DELAY_OFFSET, dq_in_group, delay);
325 }
326 
327 static void scc_mgr_set_dq_out1_delay(uint32_t dq_in_group, uint32_t delay)
328 {
329 	scc_mgr_set(SCC_MGR_IO_OUT1_DELAY_OFFSET, dq_in_group, delay);
330 }
331 
332 static void scc_mgr_set_dqs_out1_delay(uint32_t delay)
333 {
334 	scc_mgr_set(SCC_MGR_IO_OUT1_DELAY_OFFSET, rwcfg->mem_dq_per_write_dqs,
335 		    delay);
336 }
337 
338 static void scc_mgr_set_dm_out1_delay(uint32_t dm, uint32_t delay)
339 {
340 	scc_mgr_set(SCC_MGR_IO_OUT1_DELAY_OFFSET,
341 		    rwcfg->mem_dq_per_write_dqs + 1 + dm,
342 		    delay);
343 }
344 
345 /* load up dqs config settings */
346 static void scc_mgr_load_dqs(uint32_t dqs)
347 {
348 	writel(dqs, &sdr_scc_mgr->dqs_ena);
349 }
350 
351 /* load up dqs io config settings */
352 static void scc_mgr_load_dqs_io(void)
353 {
354 	writel(0, &sdr_scc_mgr->dqs_io_ena);
355 }
356 
357 /* load up dq config settings */
358 static void scc_mgr_load_dq(uint32_t dq_in_group)
359 {
360 	writel(dq_in_group, &sdr_scc_mgr->dq_ena);
361 }
362 
363 /* load up dm config settings */
364 static void scc_mgr_load_dm(uint32_t dm)
365 {
366 	writel(dm, &sdr_scc_mgr->dm_ena);
367 }
368 
369 /**
370  * scc_mgr_set_all_ranks() - Set SCC Manager register for all ranks
371  * @off:	Base offset in SCC Manager space
372  * @grp:	Read/Write group
373  * @val:	Value to be set
374  * @update:	If non-zero, trigger SCC Manager update for all ranks
375  *
376  * This function sets the SCC Manager (Scan Chain Control Manager) register
377  * and optionally triggers the SCC update for all ranks.
378  */
379 static void scc_mgr_set_all_ranks(const u32 off, const u32 grp, const u32 val,
380 				  const int update)
381 {
382 	u32 r;
383 
384 	for (r = 0; r < rwcfg->mem_number_of_ranks;
385 	     r += NUM_RANKS_PER_SHADOW_REG) {
386 		scc_mgr_set(off, grp, val);
387 
388 		if (update || (r == 0)) {
389 			writel(grp, &sdr_scc_mgr->dqs_ena);
390 			writel(0, &sdr_scc_mgr->update);
391 		}
392 	}
393 }
394 
395 static void scc_mgr_set_dqs_en_phase_all_ranks(u32 read_group, u32 phase)
396 {
397 	/*
398 	 * USER although the h/w doesn't support different phases per
399 	 * shadow register, for simplicity our scc manager modeling
400 	 * keeps different phase settings per shadow reg, and it's
401 	 * important for us to keep them in sync to match h/w.
402 	 * for efficiency, the scan chain update should occur only
403 	 * once to sr0.
404 	 */
405 	scc_mgr_set_all_ranks(SCC_MGR_DQS_EN_PHASE_OFFSET,
406 			      read_group, phase, 0);
407 }
408 
409 static void scc_mgr_set_dqdqs_output_phase_all_ranks(uint32_t write_group,
410 						     uint32_t phase)
411 {
412 	/*
413 	 * USER although the h/w doesn't support different phases per
414 	 * shadow register, for simplicity our scc manager modeling
415 	 * keeps different phase settings per shadow reg, and it's
416 	 * important for us to keep them in sync to match h/w.
417 	 * for efficiency, the scan chain update should occur only
418 	 * once to sr0.
419 	 */
420 	scc_mgr_set_all_ranks(SCC_MGR_DQDQS_OUT_PHASE_OFFSET,
421 			      write_group, phase, 0);
422 }
423 
424 static void scc_mgr_set_dqs_en_delay_all_ranks(uint32_t read_group,
425 					       uint32_t delay)
426 {
427 	/*
428 	 * In shadow register mode, the T11 settings are stored in
429 	 * registers in the core, which are updated by the DQS_ENA
430 	 * signals. Not issuing the SCC_MGR_UPD command allows us to
431 	 * save lots of rank switching overhead, by calling
432 	 * select_shadow_regs_for_update with update_scan_chains
433 	 * set to 0.
434 	 */
435 	scc_mgr_set_all_ranks(SCC_MGR_DQS_EN_DELAY_OFFSET,
436 			      read_group, delay, 1);
437 	writel(0, &sdr_scc_mgr->update);
438 }
439 
440 /**
441  * scc_mgr_set_oct_out1_delay() - Set OCT output delay
442  * @write_group:	Write group
443  * @delay:		Delay value
444  *
445  * This function sets the OCT output delay in SCC manager.
446  */
447 static void scc_mgr_set_oct_out1_delay(const u32 write_group, const u32 delay)
448 {
449 	const int ratio = rwcfg->mem_if_read_dqs_width /
450 			  rwcfg->mem_if_write_dqs_width;
451 	const int base = write_group * ratio;
452 	int i;
453 	/*
454 	 * Load the setting in the SCC manager
455 	 * Although OCT affects only write data, the OCT delay is controlled
456 	 * by the DQS logic block which is instantiated once per read group.
457 	 * For protocols where a write group consists of multiple read groups,
458 	 * the setting must be set multiple times.
459 	 */
460 	for (i = 0; i < ratio; i++)
461 		scc_mgr_set(SCC_MGR_OCT_OUT1_DELAY_OFFSET, base + i, delay);
462 }
463 
464 /**
465  * scc_mgr_set_hhp_extras() - Set HHP extras.
466  *
467  * Load the fixed setting in the SCC manager HHP extras.
468  */
469 static void scc_mgr_set_hhp_extras(void)
470 {
471 	/*
472 	 * Load the fixed setting in the SCC manager
473 	 * bits: 0:0 = 1'b1	- DQS bypass
474 	 * bits: 1:1 = 1'b1	- DQ bypass
475 	 * bits: 4:2 = 3'b001	- rfifo_mode
476 	 * bits: 6:5 = 2'b01	- rfifo clock_select
477 	 * bits: 7:7 = 1'b0	- separate gating from ungating setting
478 	 * bits: 8:8 = 1'b0	- separate OE from Output delay setting
479 	 */
480 	const u32 value = (0 << 8) | (0 << 7) | (1 << 5) |
481 			  (1 << 2) | (1 << 1) | (1 << 0);
482 	const u32 addr = SDR_PHYGRP_SCCGRP_ADDRESS |
483 			 SCC_MGR_HHP_GLOBALS_OFFSET |
484 			 SCC_MGR_HHP_EXTRAS_OFFSET;
485 
486 	debug_cond(DLEVEL == 1, "%s:%d Setting HHP Extras\n",
487 		   __func__, __LINE__);
488 	writel(value, addr);
489 	debug_cond(DLEVEL == 1, "%s:%d Done Setting HHP Extras\n",
490 		   __func__, __LINE__);
491 }
492 
493 /**
494  * scc_mgr_zero_all() - Zero all DQS config
495  *
496  * Zero all DQS config.
497  */
498 static void scc_mgr_zero_all(void)
499 {
500 	int i, r;
501 
502 	/*
503 	 * USER Zero all DQS config settings, across all groups and all
504 	 * shadow registers
505 	 */
506 	for (r = 0; r < rwcfg->mem_number_of_ranks;
507 	     r += NUM_RANKS_PER_SHADOW_REG) {
508 		for (i = 0; i < rwcfg->mem_if_read_dqs_width; i++) {
509 			/*
510 			 * The phases actually don't exist on a per-rank basis,
511 			 * but there's no harm updating them several times, so
512 			 * let's keep the code simple.
513 			 */
514 			scc_mgr_set_dqs_bus_in_delay(i, iocfg->dqs_in_reserve);
515 			scc_mgr_set_dqs_en_phase(i, 0);
516 			scc_mgr_set_dqs_en_delay(i, 0);
517 		}
518 
519 		for (i = 0; i < rwcfg->mem_if_write_dqs_width; i++) {
520 			scc_mgr_set_dqdqs_output_phase(i, 0);
521 			/* Arria V/Cyclone V don't have out2. */
522 			scc_mgr_set_oct_out1_delay(i, iocfg->dqs_out_reserve);
523 		}
524 	}
525 
526 	/* Multicast to all DQS group enables. */
527 	writel(0xff, &sdr_scc_mgr->dqs_ena);
528 	writel(0, &sdr_scc_mgr->update);
529 }
530 
531 /**
532  * scc_set_bypass_mode() - Set bypass mode and trigger SCC update
533  * @write_group:	Write group
534  *
535  * Set bypass mode and trigger SCC update.
536  */
537 static void scc_set_bypass_mode(const u32 write_group)
538 {
539 	/* Multicast to all DQ enables. */
540 	writel(0xff, &sdr_scc_mgr->dq_ena);
541 	writel(0xff, &sdr_scc_mgr->dm_ena);
542 
543 	/* Update current DQS IO enable. */
544 	writel(0, &sdr_scc_mgr->dqs_io_ena);
545 
546 	/* Update the DQS logic. */
547 	writel(write_group, &sdr_scc_mgr->dqs_ena);
548 
549 	/* Hit update. */
550 	writel(0, &sdr_scc_mgr->update);
551 }
552 
553 /**
554  * scc_mgr_load_dqs_for_write_group() - Load DQS settings for Write Group
555  * @write_group:	Write group
556  *
557  * Load DQS settings for Write Group, do not trigger SCC update.
558  */
559 static void scc_mgr_load_dqs_for_write_group(const u32 write_group)
560 {
561 	const int ratio = rwcfg->mem_if_read_dqs_width /
562 			  rwcfg->mem_if_write_dqs_width;
563 	const int base = write_group * ratio;
564 	int i;
565 	/*
566 	 * Load the setting in the SCC manager
567 	 * Although OCT affects only write data, the OCT delay is controlled
568 	 * by the DQS logic block which is instantiated once per read group.
569 	 * For protocols where a write group consists of multiple read groups,
570 	 * the setting must be set multiple times.
571 	 */
572 	for (i = 0; i < ratio; i++)
573 		writel(base + i, &sdr_scc_mgr->dqs_ena);
574 }
575 
576 /**
577  * scc_mgr_zero_group() - Zero all configs for a group
578  *
579  * Zero DQ, DM, DQS and OCT configs for a group.
580  */
581 static void scc_mgr_zero_group(const u32 write_group, const int out_only)
582 {
583 	int i, r;
584 
585 	for (r = 0; r < rwcfg->mem_number_of_ranks;
586 	     r += NUM_RANKS_PER_SHADOW_REG) {
587 		/* Zero all DQ config settings. */
588 		for (i = 0; i < rwcfg->mem_dq_per_write_dqs; i++) {
589 			scc_mgr_set_dq_out1_delay(i, 0);
590 			if (!out_only)
591 				scc_mgr_set_dq_in_delay(i, 0);
592 		}
593 
594 		/* Multicast to all DQ enables. */
595 		writel(0xff, &sdr_scc_mgr->dq_ena);
596 
597 		/* Zero all DM config settings. */
598 		for (i = 0; i < RW_MGR_NUM_DM_PER_WRITE_GROUP; i++)
599 			scc_mgr_set_dm_out1_delay(i, 0);
600 
601 		/* Multicast to all DM enables. */
602 		writel(0xff, &sdr_scc_mgr->dm_ena);
603 
604 		/* Zero all DQS IO settings. */
605 		if (!out_only)
606 			scc_mgr_set_dqs_io_in_delay(0);
607 
608 		/* Arria V/Cyclone V don't have out2. */
609 		scc_mgr_set_dqs_out1_delay(iocfg->dqs_out_reserve);
610 		scc_mgr_set_oct_out1_delay(write_group, iocfg->dqs_out_reserve);
611 		scc_mgr_load_dqs_for_write_group(write_group);
612 
613 		/* Multicast to all DQS IO enables (only 1 in total). */
614 		writel(0, &sdr_scc_mgr->dqs_io_ena);
615 
616 		/* Hit update to zero everything. */
617 		writel(0, &sdr_scc_mgr->update);
618 	}
619 }
620 
621 /*
622  * apply and load a particular input delay for the DQ pins in a group
623  * group_bgn is the index of the first dq pin (in the write group)
624  */
625 static void scc_mgr_apply_group_dq_in_delay(uint32_t group_bgn, uint32_t delay)
626 {
627 	uint32_t i, p;
628 
629 	for (i = 0, p = group_bgn; i < rwcfg->mem_dq_per_read_dqs; i++, p++) {
630 		scc_mgr_set_dq_in_delay(p, delay);
631 		scc_mgr_load_dq(p);
632 	}
633 }
634 
635 /**
636  * scc_mgr_apply_group_dq_out1_delay() - Apply and load an output delay for the DQ pins in a group
637  * @delay:		Delay value
638  *
639  * Apply and load a particular output delay for the DQ pins in a group.
640  */
641 static void scc_mgr_apply_group_dq_out1_delay(const u32 delay)
642 {
643 	int i;
644 
645 	for (i = 0; i < rwcfg->mem_dq_per_write_dqs; i++) {
646 		scc_mgr_set_dq_out1_delay(i, delay);
647 		scc_mgr_load_dq(i);
648 	}
649 }
650 
651 /* apply and load a particular output delay for the DM pins in a group */
652 static void scc_mgr_apply_group_dm_out1_delay(uint32_t delay1)
653 {
654 	uint32_t i;
655 
656 	for (i = 0; i < RW_MGR_NUM_DM_PER_WRITE_GROUP; i++) {
657 		scc_mgr_set_dm_out1_delay(i, delay1);
658 		scc_mgr_load_dm(i);
659 	}
660 }
661 
662 
663 /* apply and load delay on both DQS and OCT out1 */
664 static void scc_mgr_apply_group_dqs_io_and_oct_out1(uint32_t write_group,
665 						    uint32_t delay)
666 {
667 	scc_mgr_set_dqs_out1_delay(delay);
668 	scc_mgr_load_dqs_io();
669 
670 	scc_mgr_set_oct_out1_delay(write_group, delay);
671 	scc_mgr_load_dqs_for_write_group(write_group);
672 }
673 
674 /**
675  * scc_mgr_apply_group_all_out_delay_add() - Apply a delay to the entire output side: DQ, DM, DQS, OCT
676  * @write_group:	Write group
677  * @delay:		Delay value
678  *
679  * Apply a delay to the entire output side: DQ, DM, DQS, OCT.
680  */
681 static void scc_mgr_apply_group_all_out_delay_add(const u32 write_group,
682 						  const u32 delay)
683 {
684 	u32 i, new_delay;
685 
686 	/* DQ shift */
687 	for (i = 0; i < rwcfg->mem_dq_per_write_dqs; i++)
688 		scc_mgr_load_dq(i);
689 
690 	/* DM shift */
691 	for (i = 0; i < RW_MGR_NUM_DM_PER_WRITE_GROUP; i++)
692 		scc_mgr_load_dm(i);
693 
694 	/* DQS shift */
695 	new_delay = READ_SCC_DQS_IO_OUT2_DELAY + delay;
696 	if (new_delay > iocfg->io_out2_delay_max) {
697 		debug_cond(DLEVEL == 1,
698 			   "%s:%d (%u, %u) DQS: %u > %d; adding %u to OUT1\n",
699 			   __func__, __LINE__, write_group, delay, new_delay,
700 			   iocfg->io_out2_delay_max,
701 			   new_delay - iocfg->io_out2_delay_max);
702 		new_delay -= iocfg->io_out2_delay_max;
703 		scc_mgr_set_dqs_out1_delay(new_delay);
704 	}
705 
706 	scc_mgr_load_dqs_io();
707 
708 	/* OCT shift */
709 	new_delay = READ_SCC_OCT_OUT2_DELAY + delay;
710 	if (new_delay > iocfg->io_out2_delay_max) {
711 		debug_cond(DLEVEL == 1,
712 			   "%s:%d (%u, %u) DQS: %u > %d; adding %u to OUT1\n",
713 			   __func__, __LINE__, write_group, delay,
714 			   new_delay, iocfg->io_out2_delay_max,
715 			   new_delay - iocfg->io_out2_delay_max);
716 		new_delay -= iocfg->io_out2_delay_max;
717 		scc_mgr_set_oct_out1_delay(write_group, new_delay);
718 	}
719 
720 	scc_mgr_load_dqs_for_write_group(write_group);
721 }
722 
723 /**
724  * scc_mgr_apply_group_all_out_delay_add() - Apply a delay to the entire output side to all ranks
725  * @write_group:	Write group
726  * @delay:		Delay value
727  *
728  * Apply a delay to the entire output side (DQ, DM, DQS, OCT) to all ranks.
729  */
730 static void
731 scc_mgr_apply_group_all_out_delay_add_all_ranks(const u32 write_group,
732 						const u32 delay)
733 {
734 	int r;
735 
736 	for (r = 0; r < rwcfg->mem_number_of_ranks;
737 	     r += NUM_RANKS_PER_SHADOW_REG) {
738 		scc_mgr_apply_group_all_out_delay_add(write_group, delay);
739 		writel(0, &sdr_scc_mgr->update);
740 	}
741 }
742 
743 /**
744  * set_jump_as_return() - Return instruction optimization
745  *
746  * Optimization used to recover some slots in ddr3 inst_rom could be
747  * applied to other protocols if we wanted to
748  */
749 static void set_jump_as_return(void)
750 {
751 	/*
752 	 * To save space, we replace return with jump to special shared
753 	 * RETURN instruction so we set the counter to large value so that
754 	 * we always jump.
755 	 */
756 	writel(0xff, &sdr_rw_load_mgr_regs->load_cntr0);
757 	writel(rwcfg->rreturn, &sdr_rw_load_jump_mgr_regs->load_jump_add0);
758 }
759 
760 /**
761  * delay_for_n_mem_clocks() - Delay for N memory clocks
762  * @clocks:	Length of the delay
763  *
764  * Delay for N memory clocks.
765  */
766 static void delay_for_n_mem_clocks(const u32 clocks)
767 {
768 	u32 afi_clocks;
769 	u16 c_loop;
770 	u8 inner;
771 	u8 outer;
772 
773 	debug("%s:%d: clocks=%u ... start\n", __func__, __LINE__, clocks);
774 
775 	/* Scale (rounding up) to get afi clocks. */
776 	afi_clocks = DIV_ROUND_UP(clocks, AFI_RATE_RATIO);
777 	if (afi_clocks)	/* Temporary underflow protection */
778 		afi_clocks--;
779 
780 	/*
781 	 * Note, we don't bother accounting for being off a little
782 	 * bit because of a few extra instructions in outer loops.
783 	 * Note, the loops have a test at the end, and do the test
784 	 * before the decrement, and so always perform the loop
785 	 * 1 time more than the counter value
786 	 */
787 	c_loop = afi_clocks >> 16;
788 	outer = c_loop ? 0xff : (afi_clocks >> 8);
789 	inner = outer ? 0xff : afi_clocks;
790 
791 	/*
792 	 * rom instructions are structured as follows:
793 	 *
794 	 *    IDLE_LOOP2: jnz cntr0, TARGET_A
795 	 *    IDLE_LOOP1: jnz cntr1, TARGET_B
796 	 *                return
797 	 *
798 	 * so, when doing nested loops, TARGET_A is set to IDLE_LOOP2, and
799 	 * TARGET_B is set to IDLE_LOOP2 as well
800 	 *
801 	 * if we have no outer loop, though, then we can use IDLE_LOOP1 only,
802 	 * and set TARGET_B to IDLE_LOOP1 and we skip IDLE_LOOP2 entirely
803 	 *
804 	 * a little confusing, but it helps save precious space in the inst_rom
805 	 * and sequencer rom and keeps the delays more accurate and reduces
806 	 * overhead
807 	 */
808 	if (afi_clocks < 0x100) {
809 		writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(inner),
810 			&sdr_rw_load_mgr_regs->load_cntr1);
811 
812 		writel(rwcfg->idle_loop1,
813 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
814 
815 		writel(rwcfg->idle_loop1, SDR_PHYGRP_RWMGRGRP_ADDRESS |
816 					  RW_MGR_RUN_SINGLE_GROUP_OFFSET);
817 	} else {
818 		writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(inner),
819 			&sdr_rw_load_mgr_regs->load_cntr0);
820 
821 		writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(outer),
822 			&sdr_rw_load_mgr_regs->load_cntr1);
823 
824 		writel(rwcfg->idle_loop2,
825 			&sdr_rw_load_jump_mgr_regs->load_jump_add0);
826 
827 		writel(rwcfg->idle_loop2,
828 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
829 
830 		do {
831 			writel(rwcfg->idle_loop2,
832 				SDR_PHYGRP_RWMGRGRP_ADDRESS |
833 				RW_MGR_RUN_SINGLE_GROUP_OFFSET);
834 		} while (c_loop-- != 0);
835 	}
836 	debug("%s:%d clocks=%u ... end\n", __func__, __LINE__, clocks);
837 }
838 
839 /**
840  * rw_mgr_mem_init_load_regs() - Load instruction registers
841  * @cntr0:	Counter 0 value
842  * @cntr1:	Counter 1 value
843  * @cntr2:	Counter 2 value
844  * @jump:	Jump instruction value
845  *
846  * Load instruction registers.
847  */
848 static void rw_mgr_mem_init_load_regs(u32 cntr0, u32 cntr1, u32 cntr2, u32 jump)
849 {
850 	uint32_t grpaddr = SDR_PHYGRP_RWMGRGRP_ADDRESS |
851 			   RW_MGR_RUN_SINGLE_GROUP_OFFSET;
852 
853 	/* Load counters */
854 	writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(cntr0),
855 	       &sdr_rw_load_mgr_regs->load_cntr0);
856 	writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(cntr1),
857 	       &sdr_rw_load_mgr_regs->load_cntr1);
858 	writel(SKIP_DELAY_LOOP_VALUE_OR_ZERO(cntr2),
859 	       &sdr_rw_load_mgr_regs->load_cntr2);
860 
861 	/* Load jump address */
862 	writel(jump, &sdr_rw_load_jump_mgr_regs->load_jump_add0);
863 	writel(jump, &sdr_rw_load_jump_mgr_regs->load_jump_add1);
864 	writel(jump, &sdr_rw_load_jump_mgr_regs->load_jump_add2);
865 
866 	/* Execute count instruction */
867 	writel(jump, grpaddr);
868 }
869 
870 /**
871  * rw_mgr_mem_load_user() - Load user calibration values
872  * @fin1:	Final instruction 1
873  * @fin2:	Final instruction 2
874  * @precharge:	If 1, precharge the banks at the end
875  *
876  * Load user calibration values and optionally precharge the banks.
877  */
878 static void rw_mgr_mem_load_user(const u32 fin1, const u32 fin2,
879 				 const int precharge)
880 {
881 	u32 grpaddr = SDR_PHYGRP_RWMGRGRP_ADDRESS |
882 		      RW_MGR_RUN_SINGLE_GROUP_OFFSET;
883 	u32 r;
884 
885 	for (r = 0; r < rwcfg->mem_number_of_ranks; r++) {
886 		/* set rank */
887 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_OFF);
888 
889 		/* precharge all banks ... */
890 		if (precharge)
891 			writel(rwcfg->precharge_all, grpaddr);
892 
893 		/*
894 		 * USER Use Mirror-ed commands for odd ranks if address
895 		 * mirrorring is on
896 		 */
897 		if ((rwcfg->mem_address_mirroring >> r) & 0x1) {
898 			set_jump_as_return();
899 			writel(rwcfg->mrs2_mirr, grpaddr);
900 			delay_for_n_mem_clocks(4);
901 			set_jump_as_return();
902 			writel(rwcfg->mrs3_mirr, grpaddr);
903 			delay_for_n_mem_clocks(4);
904 			set_jump_as_return();
905 			writel(rwcfg->mrs1_mirr, grpaddr);
906 			delay_for_n_mem_clocks(4);
907 			set_jump_as_return();
908 			writel(fin1, grpaddr);
909 		} else {
910 			set_jump_as_return();
911 			writel(rwcfg->mrs2, grpaddr);
912 			delay_for_n_mem_clocks(4);
913 			set_jump_as_return();
914 			writel(rwcfg->mrs3, grpaddr);
915 			delay_for_n_mem_clocks(4);
916 			set_jump_as_return();
917 			writel(rwcfg->mrs1, grpaddr);
918 			set_jump_as_return();
919 			writel(fin2, grpaddr);
920 		}
921 
922 		if (precharge)
923 			continue;
924 
925 		set_jump_as_return();
926 		writel(rwcfg->zqcl, grpaddr);
927 
928 		/* tZQinit = tDLLK = 512 ck cycles */
929 		delay_for_n_mem_clocks(512);
930 	}
931 }
932 
933 /**
934  * rw_mgr_mem_initialize() - Initialize RW Manager
935  *
936  * Initialize RW Manager.
937  */
938 static void rw_mgr_mem_initialize(void)
939 {
940 	debug("%s:%d\n", __func__, __LINE__);
941 
942 	/* The reset / cke part of initialization is broadcasted to all ranks */
943 	writel(RW_MGR_RANK_ALL, SDR_PHYGRP_RWMGRGRP_ADDRESS |
944 				RW_MGR_SET_CS_AND_ODT_MASK_OFFSET);
945 
946 	/*
947 	 * Here's how you load register for a loop
948 	 * Counters are located @ 0x800
949 	 * Jump address are located @ 0xC00
950 	 * For both, registers 0 to 3 are selected using bits 3 and 2, like
951 	 * in 0x800, 0x804, 0x808, 0x80C and 0xC00, 0xC04, 0xC08, 0xC0C
952 	 * I know this ain't pretty, but Avalon bus throws away the 2 least
953 	 * significant bits
954 	 */
955 
956 	/* Start with memory RESET activated */
957 
958 	/* tINIT = 200us */
959 
960 	/*
961 	 * 200us @ 266MHz (3.75 ns) ~ 54000 clock cycles
962 	 * If a and b are the number of iteration in 2 nested loops
963 	 * it takes the following number of cycles to complete the operation:
964 	 * number_of_cycles = ((2 + n) * a + 2) * b
965 	 * where n is the number of instruction in the inner loop
966 	 * One possible solution is n = 0 , a = 256 , b = 106 => a = FF,
967 	 * b = 6A
968 	 */
969 	rw_mgr_mem_init_load_regs(TINIT_CNTR0_VAL, TINIT_CNTR1_VAL,
970 				  TINIT_CNTR2_VAL,
971 				  rwcfg->init_reset_0_cke_0);
972 
973 	/* Indicate that memory is stable. */
974 	writel(1, &phy_mgr_cfg->reset_mem_stbl);
975 
976 	/*
977 	 * transition the RESET to high
978 	 * Wait for 500us
979 	 */
980 
981 	/*
982 	 * 500us @ 266MHz (3.75 ns) ~ 134000 clock cycles
983 	 * If a and b are the number of iteration in 2 nested loops
984 	 * it takes the following number of cycles to complete the operation
985 	 * number_of_cycles = ((2 + n) * a + 2) * b
986 	 * where n is the number of instruction in the inner loop
987 	 * One possible solution is n = 2 , a = 131 , b = 256 => a = 83,
988 	 * b = FF
989 	 */
990 	rw_mgr_mem_init_load_regs(TRESET_CNTR0_VAL, TRESET_CNTR1_VAL,
991 				  TRESET_CNTR2_VAL,
992 				  rwcfg->init_reset_1_cke_0);
993 
994 	/* Bring up clock enable. */
995 
996 	/* tXRP < 250 ck cycles */
997 	delay_for_n_mem_clocks(250);
998 
999 	rw_mgr_mem_load_user(rwcfg->mrs0_dll_reset_mirr, rwcfg->mrs0_dll_reset,
1000 			     0);
1001 }
1002 
1003 /**
1004  * rw_mgr_mem_handoff() - Hand off the memory to user
1005  *
1006  * At the end of calibration we have to program the user settings in
1007  * and hand off the memory to the user.
1008  */
1009 static void rw_mgr_mem_handoff(void)
1010 {
1011 	rw_mgr_mem_load_user(rwcfg->mrs0_user_mirr, rwcfg->mrs0_user, 1);
1012 	/*
1013 	 * Need to wait tMOD (12CK or 15ns) time before issuing other
1014 	 * commands, but we will have plenty of NIOS cycles before actual
1015 	 * handoff so its okay.
1016 	 */
1017 }
1018 
1019 /**
1020  * rw_mgr_mem_calibrate_write_test_issue() - Issue write test command
1021  * @group:	Write Group
1022  * @use_dm:	Use DM
1023  *
1024  * Issue write test command. Two variants are provided, one that just tests
1025  * a write pattern and another that tests datamask functionality.
1026  */
1027 static void rw_mgr_mem_calibrate_write_test_issue(u32 group,
1028 						  u32 test_dm)
1029 {
1030 	const u32 quick_write_mode =
1031 		(STATIC_CALIB_STEPS & CALIB_SKIP_WRITES) &&
1032 		ENABLE_SUPER_QUICK_CALIBRATION;
1033 	u32 mcc_instruction;
1034 	u32 rw_wl_nop_cycles;
1035 
1036 	/*
1037 	 * Set counter and jump addresses for the right
1038 	 * number of NOP cycles.
1039 	 * The number of supported NOP cycles can range from -1 to infinity
1040 	 * Three different cases are handled:
1041 	 *
1042 	 * 1. For a number of NOP cycles greater than 0, the RW Mgr looping
1043 	 *    mechanism will be used to insert the right number of NOPs
1044 	 *
1045 	 * 2. For a number of NOP cycles equals to 0, the micro-instruction
1046 	 *    issuing the write command will jump straight to the
1047 	 *    micro-instruction that turns on DQS (for DDRx), or outputs write
1048 	 *    data (for RLD), skipping
1049 	 *    the NOP micro-instruction all together
1050 	 *
1051 	 * 3. A number of NOP cycles equal to -1 indicates that DQS must be
1052 	 *    turned on in the same micro-instruction that issues the write
1053 	 *    command. Then we need
1054 	 *    to directly jump to the micro-instruction that sends out the data
1055 	 *
1056 	 * NOTE: Implementing this mechanism uses 2 RW Mgr jump-counters
1057 	 *       (2 and 3). One jump-counter (0) is used to perform multiple
1058 	 *       write-read operations.
1059 	 *       one counter left to issue this command in "multiple-group" mode
1060 	 */
1061 
1062 	rw_wl_nop_cycles = gbl->rw_wl_nop_cycles;
1063 
1064 	if (rw_wl_nop_cycles == -1) {
1065 		/*
1066 		 * CNTR 2 - We want to execute the special write operation that
1067 		 * turns on DQS right away and then skip directly to the
1068 		 * instruction that sends out the data. We set the counter to a
1069 		 * large number so that the jump is always taken.
1070 		 */
1071 		writel(0xFF, &sdr_rw_load_mgr_regs->load_cntr2);
1072 
1073 		/* CNTR 3 - Not used */
1074 		if (test_dm) {
1075 			mcc_instruction = rwcfg->lfsr_wr_rd_dm_bank_0_wl_1;
1076 			writel(rwcfg->lfsr_wr_rd_dm_bank_0_data,
1077 			       &sdr_rw_load_jump_mgr_regs->load_jump_add2);
1078 			writel(rwcfg->lfsr_wr_rd_dm_bank_0_nop,
1079 			       &sdr_rw_load_jump_mgr_regs->load_jump_add3);
1080 		} else {
1081 			mcc_instruction = rwcfg->lfsr_wr_rd_bank_0_wl_1;
1082 			writel(rwcfg->lfsr_wr_rd_bank_0_data,
1083 				&sdr_rw_load_jump_mgr_regs->load_jump_add2);
1084 			writel(rwcfg->lfsr_wr_rd_bank_0_nop,
1085 				&sdr_rw_load_jump_mgr_regs->load_jump_add3);
1086 		}
1087 	} else if (rw_wl_nop_cycles == 0) {
1088 		/*
1089 		 * CNTR 2 - We want to skip the NOP operation and go straight
1090 		 * to the DQS enable instruction. We set the counter to a large
1091 		 * number so that the jump is always taken.
1092 		 */
1093 		writel(0xFF, &sdr_rw_load_mgr_regs->load_cntr2);
1094 
1095 		/* CNTR 3 - Not used */
1096 		if (test_dm) {
1097 			mcc_instruction = rwcfg->lfsr_wr_rd_dm_bank_0;
1098 			writel(rwcfg->lfsr_wr_rd_dm_bank_0_dqs,
1099 			       &sdr_rw_load_jump_mgr_regs->load_jump_add2);
1100 		} else {
1101 			mcc_instruction = rwcfg->lfsr_wr_rd_bank_0;
1102 			writel(rwcfg->lfsr_wr_rd_bank_0_dqs,
1103 				&sdr_rw_load_jump_mgr_regs->load_jump_add2);
1104 		}
1105 	} else {
1106 		/*
1107 		 * CNTR 2 - In this case we want to execute the next instruction
1108 		 * and NOT take the jump. So we set the counter to 0. The jump
1109 		 * address doesn't count.
1110 		 */
1111 		writel(0x0, &sdr_rw_load_mgr_regs->load_cntr2);
1112 		writel(0x0, &sdr_rw_load_jump_mgr_regs->load_jump_add2);
1113 
1114 		/*
1115 		 * CNTR 3 - Set the nop counter to the number of cycles we
1116 		 * need to loop for, minus 1.
1117 		 */
1118 		writel(rw_wl_nop_cycles - 1, &sdr_rw_load_mgr_regs->load_cntr3);
1119 		if (test_dm) {
1120 			mcc_instruction = rwcfg->lfsr_wr_rd_dm_bank_0;
1121 			writel(rwcfg->lfsr_wr_rd_dm_bank_0_nop,
1122 				&sdr_rw_load_jump_mgr_regs->load_jump_add3);
1123 		} else {
1124 			mcc_instruction = rwcfg->lfsr_wr_rd_bank_0;
1125 			writel(rwcfg->lfsr_wr_rd_bank_0_nop,
1126 				&sdr_rw_load_jump_mgr_regs->load_jump_add3);
1127 		}
1128 	}
1129 
1130 	writel(0, SDR_PHYGRP_RWMGRGRP_ADDRESS |
1131 		  RW_MGR_RESET_READ_DATAPATH_OFFSET);
1132 
1133 	if (quick_write_mode)
1134 		writel(0x08, &sdr_rw_load_mgr_regs->load_cntr0);
1135 	else
1136 		writel(0x40, &sdr_rw_load_mgr_regs->load_cntr0);
1137 
1138 	writel(mcc_instruction, &sdr_rw_load_jump_mgr_regs->load_jump_add0);
1139 
1140 	/*
1141 	 * CNTR 1 - This is used to ensure enough time elapses
1142 	 * for read data to come back.
1143 	 */
1144 	writel(0x30, &sdr_rw_load_mgr_regs->load_cntr1);
1145 
1146 	if (test_dm) {
1147 		writel(rwcfg->lfsr_wr_rd_dm_bank_0_wait,
1148 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
1149 	} else {
1150 		writel(rwcfg->lfsr_wr_rd_bank_0_wait,
1151 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
1152 	}
1153 
1154 	writel(mcc_instruction, (SDR_PHYGRP_RWMGRGRP_ADDRESS |
1155 				RW_MGR_RUN_SINGLE_GROUP_OFFSET) +
1156 				(group << 2));
1157 }
1158 
1159 /**
1160  * rw_mgr_mem_calibrate_write_test() - Test writes, check for single/multiple pass
1161  * @rank_bgn:		Rank number
1162  * @write_group:	Write Group
1163  * @use_dm:		Use DM
1164  * @all_correct:	All bits must be correct in the mask
1165  * @bit_chk:		Resulting bit mask after the test
1166  * @all_ranks:		Test all ranks
1167  *
1168  * Test writes, can check for a single bit pass or multiple bit pass.
1169  */
1170 static int
1171 rw_mgr_mem_calibrate_write_test(const u32 rank_bgn, const u32 write_group,
1172 				const u32 use_dm, const u32 all_correct,
1173 				u32 *bit_chk, const u32 all_ranks)
1174 {
1175 	const u32 rank_end = all_ranks ?
1176 				rwcfg->mem_number_of_ranks :
1177 				(rank_bgn + NUM_RANKS_PER_SHADOW_REG);
1178 	const u32 shift_ratio = rwcfg->mem_dq_per_write_dqs /
1179 				rwcfg->mem_virtual_groups_per_write_dqs;
1180 	const u32 correct_mask_vg = param->write_correct_mask_vg;
1181 
1182 	u32 tmp_bit_chk, base_rw_mgr;
1183 	int vg, r;
1184 
1185 	*bit_chk = param->write_correct_mask;
1186 
1187 	for (r = rank_bgn; r < rank_end; r++) {
1188 		/* Set rank */
1189 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_READ_WRITE);
1190 
1191 		tmp_bit_chk = 0;
1192 		for (vg = rwcfg->mem_virtual_groups_per_write_dqs - 1;
1193 		     vg >= 0; vg--) {
1194 			/* Reset the FIFOs to get pointers to known state. */
1195 			writel(0, &phy_mgr_cmd->fifo_reset);
1196 
1197 			rw_mgr_mem_calibrate_write_test_issue(
1198 				write_group *
1199 				rwcfg->mem_virtual_groups_per_write_dqs + vg,
1200 				use_dm);
1201 
1202 			base_rw_mgr = readl(SDR_PHYGRP_RWMGRGRP_ADDRESS);
1203 			tmp_bit_chk <<= shift_ratio;
1204 			tmp_bit_chk |= (correct_mask_vg & ~(base_rw_mgr));
1205 		}
1206 
1207 		*bit_chk &= tmp_bit_chk;
1208 	}
1209 
1210 	set_rank_and_odt_mask(0, RW_MGR_ODT_MODE_OFF);
1211 	if (all_correct) {
1212 		debug_cond(DLEVEL == 2,
1213 			   "write_test(%u,%u,ALL) : %u == %u => %i\n",
1214 			   write_group, use_dm, *bit_chk,
1215 			   param->write_correct_mask,
1216 			   *bit_chk == param->write_correct_mask);
1217 		return *bit_chk == param->write_correct_mask;
1218 	} else {
1219 		set_rank_and_odt_mask(0, RW_MGR_ODT_MODE_OFF);
1220 		debug_cond(DLEVEL == 2,
1221 			   "write_test(%u,%u,ONE) : %u != %i => %i\n",
1222 			   write_group, use_dm, *bit_chk, 0, *bit_chk != 0);
1223 		return *bit_chk != 0x00;
1224 	}
1225 }
1226 
1227 /**
1228  * rw_mgr_mem_calibrate_read_test_patterns() - Read back test patterns
1229  * @rank_bgn:	Rank number
1230  * @group:	Read/Write Group
1231  * @all_ranks:	Test all ranks
1232  *
1233  * Performs a guaranteed read on the patterns we are going to use during a
1234  * read test to ensure memory works.
1235  */
1236 static int
1237 rw_mgr_mem_calibrate_read_test_patterns(const u32 rank_bgn, const u32 group,
1238 					const u32 all_ranks)
1239 {
1240 	const u32 addr = SDR_PHYGRP_RWMGRGRP_ADDRESS |
1241 			 RW_MGR_RUN_SINGLE_GROUP_OFFSET;
1242 	const u32 addr_offset =
1243 			 (group * rwcfg->mem_virtual_groups_per_read_dqs) << 2;
1244 	const u32 rank_end = all_ranks ?
1245 				rwcfg->mem_number_of_ranks :
1246 				(rank_bgn + NUM_RANKS_PER_SHADOW_REG);
1247 	const u32 shift_ratio = rwcfg->mem_dq_per_read_dqs /
1248 				rwcfg->mem_virtual_groups_per_read_dqs;
1249 	const u32 correct_mask_vg = param->read_correct_mask_vg;
1250 
1251 	u32 tmp_bit_chk, base_rw_mgr, bit_chk;
1252 	int vg, r;
1253 	int ret = 0;
1254 
1255 	bit_chk = param->read_correct_mask;
1256 
1257 	for (r = rank_bgn; r < rank_end; r++) {
1258 		/* Set rank */
1259 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_READ_WRITE);
1260 
1261 		/* Load up a constant bursts of read commands */
1262 		writel(0x20, &sdr_rw_load_mgr_regs->load_cntr0);
1263 		writel(rwcfg->guaranteed_read,
1264 			&sdr_rw_load_jump_mgr_regs->load_jump_add0);
1265 
1266 		writel(0x20, &sdr_rw_load_mgr_regs->load_cntr1);
1267 		writel(rwcfg->guaranteed_read_cont,
1268 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
1269 
1270 		tmp_bit_chk = 0;
1271 		for (vg = rwcfg->mem_virtual_groups_per_read_dqs - 1;
1272 		     vg >= 0; vg--) {
1273 			/* Reset the FIFOs to get pointers to known state. */
1274 			writel(0, &phy_mgr_cmd->fifo_reset);
1275 			writel(0, SDR_PHYGRP_RWMGRGRP_ADDRESS |
1276 				  RW_MGR_RESET_READ_DATAPATH_OFFSET);
1277 			writel(rwcfg->guaranteed_read,
1278 			       addr + addr_offset + (vg << 2));
1279 
1280 			base_rw_mgr = readl(SDR_PHYGRP_RWMGRGRP_ADDRESS);
1281 			tmp_bit_chk <<= shift_ratio;
1282 			tmp_bit_chk |= correct_mask_vg & ~base_rw_mgr;
1283 		}
1284 
1285 		bit_chk &= tmp_bit_chk;
1286 	}
1287 
1288 	writel(rwcfg->clear_dqs_enable, addr + (group << 2));
1289 
1290 	set_rank_and_odt_mask(0, RW_MGR_ODT_MODE_OFF);
1291 
1292 	if (bit_chk != param->read_correct_mask)
1293 		ret = -EIO;
1294 
1295 	debug_cond(DLEVEL == 1,
1296 		   "%s:%d test_load_patterns(%u,ALL) => (%u == %u) => %i\n",
1297 		   __func__, __LINE__, group, bit_chk,
1298 		   param->read_correct_mask, ret);
1299 
1300 	return ret;
1301 }
1302 
1303 /**
1304  * rw_mgr_mem_calibrate_read_load_patterns() - Load up the patterns for read test
1305  * @rank_bgn:	Rank number
1306  * @all_ranks:	Test all ranks
1307  *
1308  * Load up the patterns we are going to use during a read test.
1309  */
1310 static void rw_mgr_mem_calibrate_read_load_patterns(const u32 rank_bgn,
1311 						    const int all_ranks)
1312 {
1313 	const u32 rank_end = all_ranks ?
1314 			rwcfg->mem_number_of_ranks :
1315 			(rank_bgn + NUM_RANKS_PER_SHADOW_REG);
1316 	u32 r;
1317 
1318 	debug("%s:%d\n", __func__, __LINE__);
1319 
1320 	for (r = rank_bgn; r < rank_end; r++) {
1321 		/* set rank */
1322 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_READ_WRITE);
1323 
1324 		/* Load up a constant bursts */
1325 		writel(0x20, &sdr_rw_load_mgr_regs->load_cntr0);
1326 
1327 		writel(rwcfg->guaranteed_write_wait0,
1328 			&sdr_rw_load_jump_mgr_regs->load_jump_add0);
1329 
1330 		writel(0x20, &sdr_rw_load_mgr_regs->load_cntr1);
1331 
1332 		writel(rwcfg->guaranteed_write_wait1,
1333 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
1334 
1335 		writel(0x04, &sdr_rw_load_mgr_regs->load_cntr2);
1336 
1337 		writel(rwcfg->guaranteed_write_wait2,
1338 			&sdr_rw_load_jump_mgr_regs->load_jump_add2);
1339 
1340 		writel(0x04, &sdr_rw_load_mgr_regs->load_cntr3);
1341 
1342 		writel(rwcfg->guaranteed_write_wait3,
1343 			&sdr_rw_load_jump_mgr_regs->load_jump_add3);
1344 
1345 		writel(rwcfg->guaranteed_write, SDR_PHYGRP_RWMGRGRP_ADDRESS |
1346 						RW_MGR_RUN_SINGLE_GROUP_OFFSET);
1347 	}
1348 
1349 	set_rank_and_odt_mask(0, RW_MGR_ODT_MODE_OFF);
1350 }
1351 
1352 /**
1353  * rw_mgr_mem_calibrate_read_test() - Perform READ test on single rank
1354  * @rank_bgn:		Rank number
1355  * @group:		Read/Write group
1356  * @num_tries:		Number of retries of the test
1357  * @all_correct:	All bits must be correct in the mask
1358  * @bit_chk:		Resulting bit mask after the test
1359  * @all_groups:		Test all R/W groups
1360  * @all_ranks:		Test all ranks
1361  *
1362  * Try a read and see if it returns correct data back. Test has dummy reads
1363  * inserted into the mix used to align DQS enable. Test has more thorough
1364  * checks than the regular read test.
1365  */
1366 static int
1367 rw_mgr_mem_calibrate_read_test(const u32 rank_bgn, const u32 group,
1368 			       const u32 num_tries, const u32 all_correct,
1369 			       u32 *bit_chk,
1370 			       const u32 all_groups, const u32 all_ranks)
1371 {
1372 	const u32 rank_end = all_ranks ? rwcfg->mem_number_of_ranks :
1373 		(rank_bgn + NUM_RANKS_PER_SHADOW_REG);
1374 	const u32 quick_read_mode =
1375 		((STATIC_CALIB_STEPS & CALIB_SKIP_DELAY_SWEEPS) &&
1376 		 ENABLE_SUPER_QUICK_CALIBRATION);
1377 	u32 correct_mask_vg = param->read_correct_mask_vg;
1378 	u32 tmp_bit_chk;
1379 	u32 base_rw_mgr;
1380 	u32 addr;
1381 
1382 	int r, vg, ret;
1383 
1384 	*bit_chk = param->read_correct_mask;
1385 
1386 	for (r = rank_bgn; r < rank_end; r++) {
1387 		/* set rank */
1388 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_READ_WRITE);
1389 
1390 		writel(0x10, &sdr_rw_load_mgr_regs->load_cntr1);
1391 
1392 		writel(rwcfg->read_b2b_wait1,
1393 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
1394 
1395 		writel(0x10, &sdr_rw_load_mgr_regs->load_cntr2);
1396 		writel(rwcfg->read_b2b_wait2,
1397 			&sdr_rw_load_jump_mgr_regs->load_jump_add2);
1398 
1399 		if (quick_read_mode)
1400 			writel(0x1, &sdr_rw_load_mgr_regs->load_cntr0);
1401 			/* need at least two (1+1) reads to capture failures */
1402 		else if (all_groups)
1403 			writel(0x06, &sdr_rw_load_mgr_regs->load_cntr0);
1404 		else
1405 			writel(0x32, &sdr_rw_load_mgr_regs->load_cntr0);
1406 
1407 		writel(rwcfg->read_b2b,
1408 			&sdr_rw_load_jump_mgr_regs->load_jump_add0);
1409 		if (all_groups)
1410 			writel(rwcfg->mem_if_read_dqs_width *
1411 			       rwcfg->mem_virtual_groups_per_read_dqs - 1,
1412 			       &sdr_rw_load_mgr_regs->load_cntr3);
1413 		else
1414 			writel(0x0, &sdr_rw_load_mgr_regs->load_cntr3);
1415 
1416 		writel(rwcfg->read_b2b,
1417 			&sdr_rw_load_jump_mgr_regs->load_jump_add3);
1418 
1419 		tmp_bit_chk = 0;
1420 		for (vg = rwcfg->mem_virtual_groups_per_read_dqs - 1; vg >= 0;
1421 		     vg--) {
1422 			/* Reset the FIFOs to get pointers to known state. */
1423 			writel(0, &phy_mgr_cmd->fifo_reset);
1424 			writel(0, SDR_PHYGRP_RWMGRGRP_ADDRESS |
1425 				  RW_MGR_RESET_READ_DATAPATH_OFFSET);
1426 
1427 			if (all_groups) {
1428 				addr = SDR_PHYGRP_RWMGRGRP_ADDRESS |
1429 				       RW_MGR_RUN_ALL_GROUPS_OFFSET;
1430 			} else {
1431 				addr = SDR_PHYGRP_RWMGRGRP_ADDRESS |
1432 				       RW_MGR_RUN_SINGLE_GROUP_OFFSET;
1433 			}
1434 
1435 			writel(rwcfg->read_b2b, addr +
1436 			       ((group * rwcfg->mem_virtual_groups_per_read_dqs +
1437 			       vg) << 2));
1438 
1439 			base_rw_mgr = readl(SDR_PHYGRP_RWMGRGRP_ADDRESS);
1440 			tmp_bit_chk <<= rwcfg->mem_dq_per_read_dqs /
1441 					rwcfg->mem_virtual_groups_per_read_dqs;
1442 			tmp_bit_chk |= correct_mask_vg & ~(base_rw_mgr);
1443 		}
1444 
1445 		*bit_chk &= tmp_bit_chk;
1446 	}
1447 
1448 	addr = SDR_PHYGRP_RWMGRGRP_ADDRESS | RW_MGR_RUN_SINGLE_GROUP_OFFSET;
1449 	writel(rwcfg->clear_dqs_enable, addr + (group << 2));
1450 
1451 	set_rank_and_odt_mask(0, RW_MGR_ODT_MODE_OFF);
1452 
1453 	if (all_correct) {
1454 		ret = (*bit_chk == param->read_correct_mask);
1455 		debug_cond(DLEVEL == 2,
1456 			   "%s:%d read_test(%u,ALL,%u) => (%u == %u) => %i\n",
1457 			   __func__, __LINE__, group, all_groups, *bit_chk,
1458 			   param->read_correct_mask, ret);
1459 	} else	{
1460 		ret = (*bit_chk != 0x00);
1461 		debug_cond(DLEVEL == 2,
1462 			   "%s:%d read_test(%u,ONE,%u) => (%u != %u) => %i\n",
1463 			   __func__, __LINE__, group, all_groups, *bit_chk,
1464 			   0, ret);
1465 	}
1466 
1467 	return ret;
1468 }
1469 
1470 /**
1471  * rw_mgr_mem_calibrate_read_test_all_ranks() - Perform READ test on all ranks
1472  * @grp:		Read/Write group
1473  * @num_tries:		Number of retries of the test
1474  * @all_correct:	All bits must be correct in the mask
1475  * @all_groups:		Test all R/W groups
1476  *
1477  * Perform a READ test across all memory ranks.
1478  */
1479 static int
1480 rw_mgr_mem_calibrate_read_test_all_ranks(const u32 grp, const u32 num_tries,
1481 					 const u32 all_correct,
1482 					 const u32 all_groups)
1483 {
1484 	u32 bit_chk;
1485 	return rw_mgr_mem_calibrate_read_test(0, grp, num_tries, all_correct,
1486 					      &bit_chk, all_groups, 1);
1487 }
1488 
1489 /**
1490  * rw_mgr_incr_vfifo() - Increase VFIFO value
1491  * @grp:	Read/Write group
1492  *
1493  * Increase VFIFO value.
1494  */
1495 static void rw_mgr_incr_vfifo(const u32 grp)
1496 {
1497 	writel(grp, &phy_mgr_cmd->inc_vfifo_hard_phy);
1498 }
1499 
1500 /**
1501  * rw_mgr_decr_vfifo() - Decrease VFIFO value
1502  * @grp:	Read/Write group
1503  *
1504  * Decrease VFIFO value.
1505  */
1506 static void rw_mgr_decr_vfifo(const u32 grp)
1507 {
1508 	u32 i;
1509 
1510 	for (i = 0; i < READ_VALID_FIFO_SIZE - 1; i++)
1511 		rw_mgr_incr_vfifo(grp);
1512 }
1513 
1514 /**
1515  * find_vfifo_failing_read() - Push VFIFO to get a failing read
1516  * @grp:	Read/Write group
1517  *
1518  * Push VFIFO until a failing read happens.
1519  */
1520 static int find_vfifo_failing_read(const u32 grp)
1521 {
1522 	u32 v, ret, fail_cnt = 0;
1523 
1524 	for (v = 0; v < READ_VALID_FIFO_SIZE; v++) {
1525 		debug_cond(DLEVEL == 2, "%s:%d: vfifo %u\n",
1526 			   __func__, __LINE__, v);
1527 		ret = rw_mgr_mem_calibrate_read_test_all_ranks(grp, 1,
1528 						PASS_ONE_BIT, 0);
1529 		if (!ret) {
1530 			fail_cnt++;
1531 
1532 			if (fail_cnt == 2)
1533 				return v;
1534 		}
1535 
1536 		/* Fiddle with FIFO. */
1537 		rw_mgr_incr_vfifo(grp);
1538 	}
1539 
1540 	/* No failing read found! Something must have gone wrong. */
1541 	debug_cond(DLEVEL == 2, "%s:%d: vfifo failed\n", __func__, __LINE__);
1542 	return 0;
1543 }
1544 
1545 /**
1546  * sdr_find_phase_delay() - Find DQS enable phase or delay
1547  * @working:	If 1, look for working phase/delay, if 0, look for non-working
1548  * @delay:	If 1, look for delay, if 0, look for phase
1549  * @grp:	Read/Write group
1550  * @work:	Working window position
1551  * @work_inc:	Working window increment
1552  * @pd:		DQS Phase/Delay Iterator
1553  *
1554  * Find working or non-working DQS enable phase setting.
1555  */
1556 static int sdr_find_phase_delay(int working, int delay, const u32 grp,
1557 				u32 *work, const u32 work_inc, u32 *pd)
1558 {
1559 	const u32 max = delay ? iocfg->dqs_en_delay_max : iocfg->dqs_en_phase_max;
1560 	u32 ret;
1561 
1562 	for (; *pd <= max; (*pd)++) {
1563 		if (delay)
1564 			scc_mgr_set_dqs_en_delay_all_ranks(grp, *pd);
1565 		else
1566 			scc_mgr_set_dqs_en_phase_all_ranks(grp, *pd);
1567 
1568 		ret = rw_mgr_mem_calibrate_read_test_all_ranks(grp, 1,
1569 					PASS_ONE_BIT, 0);
1570 		if (!working)
1571 			ret = !ret;
1572 
1573 		if (ret)
1574 			return 0;
1575 
1576 		if (work)
1577 			*work += work_inc;
1578 	}
1579 
1580 	return -EINVAL;
1581 }
1582 /**
1583  * sdr_find_phase() - Find DQS enable phase
1584  * @working:	If 1, look for working phase, if 0, look for non-working phase
1585  * @grp:	Read/Write group
1586  * @work:	Working window position
1587  * @i:		Iterator
1588  * @p:		DQS Phase Iterator
1589  *
1590  * Find working or non-working DQS enable phase setting.
1591  */
1592 static int sdr_find_phase(int working, const u32 grp, u32 *work,
1593 			  u32 *i, u32 *p)
1594 {
1595 	const u32 end = READ_VALID_FIFO_SIZE + (working ? 0 : 1);
1596 	int ret;
1597 
1598 	for (; *i < end; (*i)++) {
1599 		if (working)
1600 			*p = 0;
1601 
1602 		ret = sdr_find_phase_delay(working, 0, grp, work,
1603 					   iocfg->delay_per_opa_tap, p);
1604 		if (!ret)
1605 			return 0;
1606 
1607 		if (*p > iocfg->dqs_en_phase_max) {
1608 			/* Fiddle with FIFO. */
1609 			rw_mgr_incr_vfifo(grp);
1610 			if (!working)
1611 				*p = 0;
1612 		}
1613 	}
1614 
1615 	return -EINVAL;
1616 }
1617 
1618 /**
1619  * sdr_working_phase() - Find working DQS enable phase
1620  * @grp:	Read/Write group
1621  * @work_bgn:	Working window start position
1622  * @d:		dtaps output value
1623  * @p:		DQS Phase Iterator
1624  * @i:		Iterator
1625  *
1626  * Find working DQS enable phase setting.
1627  */
1628 static int sdr_working_phase(const u32 grp, u32 *work_bgn, u32 *d,
1629 			     u32 *p, u32 *i)
1630 {
1631 	const u32 dtaps_per_ptap = iocfg->delay_per_opa_tap /
1632 				   iocfg->delay_per_dqs_en_dchain_tap;
1633 	int ret;
1634 
1635 	*work_bgn = 0;
1636 
1637 	for (*d = 0; *d <= dtaps_per_ptap; (*d)++) {
1638 		*i = 0;
1639 		scc_mgr_set_dqs_en_delay_all_ranks(grp, *d);
1640 		ret = sdr_find_phase(1, grp, work_bgn, i, p);
1641 		if (!ret)
1642 			return 0;
1643 		*work_bgn += iocfg->delay_per_dqs_en_dchain_tap;
1644 	}
1645 
1646 	/* Cannot find working solution */
1647 	debug_cond(DLEVEL == 2, "%s:%d find_dqs_en_phase: no vfifo/ptap/dtap\n",
1648 		   __func__, __LINE__);
1649 	return -EINVAL;
1650 }
1651 
1652 /**
1653  * sdr_backup_phase() - Find DQS enable backup phase
1654  * @grp:	Read/Write group
1655  * @work_bgn:	Working window start position
1656  * @p:		DQS Phase Iterator
1657  *
1658  * Find DQS enable backup phase setting.
1659  */
1660 static void sdr_backup_phase(const u32 grp, u32 *work_bgn, u32 *p)
1661 {
1662 	u32 tmp_delay, d;
1663 	int ret;
1664 
1665 	/* Special case code for backing up a phase */
1666 	if (*p == 0) {
1667 		*p = iocfg->dqs_en_phase_max;
1668 		rw_mgr_decr_vfifo(grp);
1669 	} else {
1670 		(*p)--;
1671 	}
1672 	tmp_delay = *work_bgn - iocfg->delay_per_opa_tap;
1673 	scc_mgr_set_dqs_en_phase_all_ranks(grp, *p);
1674 
1675 	for (d = 0; d <= iocfg->dqs_en_delay_max && tmp_delay < *work_bgn; d++) {
1676 		scc_mgr_set_dqs_en_delay_all_ranks(grp, d);
1677 
1678 		ret = rw_mgr_mem_calibrate_read_test_all_ranks(grp, 1,
1679 					PASS_ONE_BIT, 0);
1680 		if (ret) {
1681 			*work_bgn = tmp_delay;
1682 			break;
1683 		}
1684 
1685 		tmp_delay += iocfg->delay_per_dqs_en_dchain_tap;
1686 	}
1687 
1688 	/* Restore VFIFO to old state before we decremented it (if needed). */
1689 	(*p)++;
1690 	if (*p > iocfg->dqs_en_phase_max) {
1691 		*p = 0;
1692 		rw_mgr_incr_vfifo(grp);
1693 	}
1694 
1695 	scc_mgr_set_dqs_en_delay_all_ranks(grp, 0);
1696 }
1697 
1698 /**
1699  * sdr_nonworking_phase() - Find non-working DQS enable phase
1700  * @grp:	Read/Write group
1701  * @work_end:	Working window end position
1702  * @p:		DQS Phase Iterator
1703  * @i:		Iterator
1704  *
1705  * Find non-working DQS enable phase setting.
1706  */
1707 static int sdr_nonworking_phase(const u32 grp, u32 *work_end, u32 *p, u32 *i)
1708 {
1709 	int ret;
1710 
1711 	(*p)++;
1712 	*work_end += iocfg->delay_per_opa_tap;
1713 	if (*p > iocfg->dqs_en_phase_max) {
1714 		/* Fiddle with FIFO. */
1715 		*p = 0;
1716 		rw_mgr_incr_vfifo(grp);
1717 	}
1718 
1719 	ret = sdr_find_phase(0, grp, work_end, i, p);
1720 	if (ret) {
1721 		/* Cannot see edge of failing read. */
1722 		debug_cond(DLEVEL == 2, "%s:%d: end: failed\n",
1723 			   __func__, __LINE__);
1724 	}
1725 
1726 	return ret;
1727 }
1728 
1729 /**
1730  * sdr_find_window_center() - Find center of the working DQS window.
1731  * @grp:	Read/Write group
1732  * @work_bgn:	First working settings
1733  * @work_end:	Last working settings
1734  *
1735  * Find center of the working DQS enable window.
1736  */
1737 static int sdr_find_window_center(const u32 grp, const u32 work_bgn,
1738 				  const u32 work_end)
1739 {
1740 	u32 work_mid;
1741 	int tmp_delay = 0;
1742 	int i, p, d;
1743 
1744 	work_mid = (work_bgn + work_end) / 2;
1745 
1746 	debug_cond(DLEVEL == 2, "work_bgn=%d work_end=%d work_mid=%d\n",
1747 		   work_bgn, work_end, work_mid);
1748 	/* Get the middle delay to be less than a VFIFO delay */
1749 	tmp_delay = (iocfg->dqs_en_phase_max + 1) * iocfg->delay_per_opa_tap;
1750 
1751 	debug_cond(DLEVEL == 2, "vfifo ptap delay %d\n", tmp_delay);
1752 	work_mid %= tmp_delay;
1753 	debug_cond(DLEVEL == 2, "new work_mid %d\n", work_mid);
1754 
1755 	tmp_delay = rounddown(work_mid, iocfg->delay_per_opa_tap);
1756 	if (tmp_delay > iocfg->dqs_en_phase_max * iocfg->delay_per_opa_tap)
1757 		tmp_delay = iocfg->dqs_en_phase_max * iocfg->delay_per_opa_tap;
1758 	p = tmp_delay / iocfg->delay_per_opa_tap;
1759 
1760 	debug_cond(DLEVEL == 2, "new p %d, tmp_delay=%d\n", p, tmp_delay);
1761 
1762 	d = DIV_ROUND_UP(work_mid - tmp_delay, iocfg->delay_per_dqs_en_dchain_tap);
1763 	if (d > iocfg->dqs_en_delay_max)
1764 		d = iocfg->dqs_en_delay_max;
1765 	tmp_delay += d * iocfg->delay_per_dqs_en_dchain_tap;
1766 
1767 	debug_cond(DLEVEL == 2, "new d %d, tmp_delay=%d\n", d, tmp_delay);
1768 
1769 	scc_mgr_set_dqs_en_phase_all_ranks(grp, p);
1770 	scc_mgr_set_dqs_en_delay_all_ranks(grp, d);
1771 
1772 	/*
1773 	 * push vfifo until we can successfully calibrate. We can do this
1774 	 * because the largest possible margin in 1 VFIFO cycle.
1775 	 */
1776 	for (i = 0; i < READ_VALID_FIFO_SIZE; i++) {
1777 		debug_cond(DLEVEL == 2, "find_dqs_en_phase: center\n");
1778 		if (rw_mgr_mem_calibrate_read_test_all_ranks(grp, 1,
1779 							     PASS_ONE_BIT,
1780 							     0)) {
1781 			debug_cond(DLEVEL == 2,
1782 				   "%s:%d center: found: ptap=%u dtap=%u\n",
1783 				   __func__, __LINE__, p, d);
1784 			return 0;
1785 		}
1786 
1787 		/* Fiddle with FIFO. */
1788 		rw_mgr_incr_vfifo(grp);
1789 	}
1790 
1791 	debug_cond(DLEVEL == 2, "%s:%d center: failed.\n",
1792 		   __func__, __LINE__);
1793 	return -EINVAL;
1794 }
1795 
1796 /**
1797  * rw_mgr_mem_calibrate_vfifo_find_dqs_en_phase() - Find a good DQS enable to use
1798  * @grp:	Read/Write Group
1799  *
1800  * Find a good DQS enable to use.
1801  */
1802 static int rw_mgr_mem_calibrate_vfifo_find_dqs_en_phase(const u32 grp)
1803 {
1804 	u32 d, p, i;
1805 	u32 dtaps_per_ptap;
1806 	u32 work_bgn, work_end;
1807 	u32 found_passing_read, found_failing_read, initial_failing_dtap;
1808 	int ret;
1809 
1810 	debug("%s:%d %u\n", __func__, __LINE__, grp);
1811 
1812 	reg_file_set_sub_stage(CAL_SUBSTAGE_VFIFO_CENTER);
1813 
1814 	scc_mgr_set_dqs_en_delay_all_ranks(grp, 0);
1815 	scc_mgr_set_dqs_en_phase_all_ranks(grp, 0);
1816 
1817 	/* Step 0: Determine number of delay taps for each phase tap. */
1818 	dtaps_per_ptap = iocfg->delay_per_opa_tap / iocfg->delay_per_dqs_en_dchain_tap;
1819 
1820 	/* Step 1: First push vfifo until we get a failing read. */
1821 	find_vfifo_failing_read(grp);
1822 
1823 	/* Step 2: Find first working phase, increment in ptaps. */
1824 	work_bgn = 0;
1825 	ret = sdr_working_phase(grp, &work_bgn, &d, &p, &i);
1826 	if (ret)
1827 		return ret;
1828 
1829 	work_end = work_bgn;
1830 
1831 	/*
1832 	 * If d is 0 then the working window covers a phase tap and we can
1833 	 * follow the old procedure. Otherwise, we've found the beginning
1834 	 * and we need to increment the dtaps until we find the end.
1835 	 */
1836 	if (d == 0) {
1837 		/*
1838 		 * Step 3a: If we have room, back off by one and
1839 		 *          increment in dtaps.
1840 		 */
1841 		sdr_backup_phase(grp, &work_bgn, &p);
1842 
1843 		/*
1844 		 * Step 4a: go forward from working phase to non working
1845 		 * phase, increment in ptaps.
1846 		 */
1847 		ret = sdr_nonworking_phase(grp, &work_end, &p, &i);
1848 		if (ret)
1849 			return ret;
1850 
1851 		/* Step 5a: Back off one from last, increment in dtaps. */
1852 
1853 		/* Special case code for backing up a phase */
1854 		if (p == 0) {
1855 			p = iocfg->dqs_en_phase_max;
1856 			rw_mgr_decr_vfifo(grp);
1857 		} else {
1858 			p = p - 1;
1859 		}
1860 
1861 		work_end -= iocfg->delay_per_opa_tap;
1862 		scc_mgr_set_dqs_en_phase_all_ranks(grp, p);
1863 
1864 		d = 0;
1865 
1866 		debug_cond(DLEVEL == 2, "%s:%d p: ptap=%u\n",
1867 			   __func__, __LINE__, p);
1868 	}
1869 
1870 	/* The dtap increment to find the failing edge is done here. */
1871 	sdr_find_phase_delay(0, 1, grp, &work_end,
1872 			     iocfg->delay_per_dqs_en_dchain_tap, &d);
1873 
1874 	/* Go back to working dtap */
1875 	if (d != 0)
1876 		work_end -= iocfg->delay_per_dqs_en_dchain_tap;
1877 
1878 	debug_cond(DLEVEL == 2,
1879 		   "%s:%d p/d: ptap=%u dtap=%u end=%u\n",
1880 		   __func__, __LINE__, p, d - 1, work_end);
1881 
1882 	if (work_end < work_bgn) {
1883 		/* nil range */
1884 		debug_cond(DLEVEL == 2, "%s:%d end-2: failed\n",
1885 			   __func__, __LINE__);
1886 		return -EINVAL;
1887 	}
1888 
1889 	debug_cond(DLEVEL == 2, "%s:%d found range [%u,%u]\n",
1890 		   __func__, __LINE__, work_bgn, work_end);
1891 
1892 	/*
1893 	 * We need to calculate the number of dtaps that equal a ptap.
1894 	 * To do that we'll back up a ptap and re-find the edge of the
1895 	 * window using dtaps
1896 	 */
1897 	debug_cond(DLEVEL == 2, "%s:%d calculate dtaps_per_ptap for tracking\n",
1898 		   __func__, __LINE__);
1899 
1900 	/* Special case code for backing up a phase */
1901 	if (p == 0) {
1902 		p = iocfg->dqs_en_phase_max;
1903 		rw_mgr_decr_vfifo(grp);
1904 		debug_cond(DLEVEL == 2, "%s:%d backedup cycle/phase: p=%u\n",
1905 			   __func__, __LINE__, p);
1906 	} else {
1907 		p = p - 1;
1908 		debug_cond(DLEVEL == 2, "%s:%d backedup phase only: p=%u",
1909 			   __func__, __LINE__, p);
1910 	}
1911 
1912 	scc_mgr_set_dqs_en_phase_all_ranks(grp, p);
1913 
1914 	/*
1915 	 * Increase dtap until we first see a passing read (in case the
1916 	 * window is smaller than a ptap), and then a failing read to
1917 	 * mark the edge of the window again.
1918 	 */
1919 
1920 	/* Find a passing read. */
1921 	debug_cond(DLEVEL == 2, "%s:%d find passing read\n",
1922 		   __func__, __LINE__);
1923 
1924 	initial_failing_dtap = d;
1925 
1926 	found_passing_read = !sdr_find_phase_delay(1, 1, grp, NULL, 0, &d);
1927 	if (found_passing_read) {
1928 		/* Find a failing read. */
1929 		debug_cond(DLEVEL == 2, "%s:%d find failing read\n",
1930 			   __func__, __LINE__);
1931 		d++;
1932 		found_failing_read = !sdr_find_phase_delay(0, 1, grp, NULL, 0,
1933 							   &d);
1934 	} else {
1935 		debug_cond(DLEVEL == 1,
1936 			   "%s:%d failed to calculate dtaps per ptap. Fall back on static value\n",
1937 			   __func__, __LINE__);
1938 	}
1939 
1940 	/*
1941 	 * The dynamically calculated dtaps_per_ptap is only valid if we
1942 	 * found a passing/failing read. If we didn't, it means d hit the max
1943 	 * (iocfg->dqs_en_delay_max). Otherwise, dtaps_per_ptap retains its
1944 	 * statically calculated value.
1945 	 */
1946 	if (found_passing_read && found_failing_read)
1947 		dtaps_per_ptap = d - initial_failing_dtap;
1948 
1949 	writel(dtaps_per_ptap, &sdr_reg_file->dtaps_per_ptap);
1950 	debug_cond(DLEVEL == 2, "%s:%d dtaps_per_ptap=%u - %u = %u",
1951 		   __func__, __LINE__, d, initial_failing_dtap, dtaps_per_ptap);
1952 
1953 	/* Step 6: Find the centre of the window. */
1954 	ret = sdr_find_window_center(grp, work_bgn, work_end);
1955 
1956 	return ret;
1957 }
1958 
1959 /**
1960  * search_stop_check() - Check if the detected edge is valid
1961  * @write:		Perform read (Stage 2) or write (Stage 3) calibration
1962  * @d:			DQS delay
1963  * @rank_bgn:		Rank number
1964  * @write_group:	Write Group
1965  * @read_group:		Read Group
1966  * @bit_chk:		Resulting bit mask after the test
1967  * @sticky_bit_chk:	Resulting sticky bit mask after the test
1968  * @use_read_test:	Perform read test
1969  *
1970  * Test if the found edge is valid.
1971  */
1972 static u32 search_stop_check(const int write, const int d, const int rank_bgn,
1973 			     const u32 write_group, const u32 read_group,
1974 			     u32 *bit_chk, u32 *sticky_bit_chk,
1975 			     const u32 use_read_test)
1976 {
1977 	const u32 ratio = rwcfg->mem_if_read_dqs_width /
1978 			  rwcfg->mem_if_write_dqs_width;
1979 	const u32 correct_mask = write ? param->write_correct_mask :
1980 					 param->read_correct_mask;
1981 	const u32 per_dqs = write ? rwcfg->mem_dq_per_write_dqs :
1982 				    rwcfg->mem_dq_per_read_dqs;
1983 	u32 ret;
1984 	/*
1985 	 * Stop searching when the read test doesn't pass AND when
1986 	 * we've seen a passing read on every bit.
1987 	 */
1988 	if (write) {			/* WRITE-ONLY */
1989 		ret = !rw_mgr_mem_calibrate_write_test(rank_bgn, write_group,
1990 							 0, PASS_ONE_BIT,
1991 							 bit_chk, 0);
1992 	} else if (use_read_test) {	/* READ-ONLY */
1993 		ret = !rw_mgr_mem_calibrate_read_test(rank_bgn, read_group,
1994 							NUM_READ_PB_TESTS,
1995 							PASS_ONE_BIT, bit_chk,
1996 							0, 0);
1997 	} else {			/* READ-ONLY */
1998 		rw_mgr_mem_calibrate_write_test(rank_bgn, write_group, 0,
1999 						PASS_ONE_BIT, bit_chk, 0);
2000 		*bit_chk = *bit_chk >> (per_dqs *
2001 			(read_group - (write_group * ratio)));
2002 		ret = (*bit_chk == 0);
2003 	}
2004 	*sticky_bit_chk = *sticky_bit_chk | *bit_chk;
2005 	ret = ret && (*sticky_bit_chk == correct_mask);
2006 	debug_cond(DLEVEL == 2,
2007 		   "%s:%d center(left): dtap=%u => %u == %u && %u",
2008 		   __func__, __LINE__, d,
2009 		   *sticky_bit_chk, correct_mask, ret);
2010 	return ret;
2011 }
2012 
2013 /**
2014  * search_left_edge() - Find left edge of DQ/DQS working phase
2015  * @write:		Perform read (Stage 2) or write (Stage 3) calibration
2016  * @rank_bgn:		Rank number
2017  * @write_group:	Write Group
2018  * @read_group:		Read Group
2019  * @test_bgn:		Rank number to begin the test
2020  * @sticky_bit_chk:	Resulting sticky bit mask after the test
2021  * @left_edge:		Left edge of the DQ/DQS phase
2022  * @right_edge:		Right edge of the DQ/DQS phase
2023  * @use_read_test:	Perform read test
2024  *
2025  * Find left edge of DQ/DQS working phase.
2026  */
2027 static void search_left_edge(const int write, const int rank_bgn,
2028 	const u32 write_group, const u32 read_group, const u32 test_bgn,
2029 	u32 *sticky_bit_chk,
2030 	int *left_edge, int *right_edge, const u32 use_read_test)
2031 {
2032 	const u32 delay_max = write ? iocfg->io_out1_delay_max : iocfg->io_in_delay_max;
2033 	const u32 dqs_max = write ? iocfg->io_out1_delay_max : iocfg->dqs_in_delay_max;
2034 	const u32 per_dqs = write ? rwcfg->mem_dq_per_write_dqs :
2035 				    rwcfg->mem_dq_per_read_dqs;
2036 	u32 stop, bit_chk;
2037 	int i, d;
2038 
2039 	for (d = 0; d <= dqs_max; d++) {
2040 		if (write)
2041 			scc_mgr_apply_group_dq_out1_delay(d);
2042 		else
2043 			scc_mgr_apply_group_dq_in_delay(test_bgn, d);
2044 
2045 		writel(0, &sdr_scc_mgr->update);
2046 
2047 		stop = search_stop_check(write, d, rank_bgn, write_group,
2048 					 read_group, &bit_chk, sticky_bit_chk,
2049 					 use_read_test);
2050 		if (stop == 1)
2051 			break;
2052 
2053 		/* stop != 1 */
2054 		for (i = 0; i < per_dqs; i++) {
2055 			if (bit_chk & 1) {
2056 				/*
2057 				 * Remember a passing test as
2058 				 * the left_edge.
2059 				 */
2060 				left_edge[i] = d;
2061 			} else {
2062 				/*
2063 				 * If a left edge has not been seen
2064 				 * yet, then a future passing test
2065 				 * will mark this edge as the right
2066 				 * edge.
2067 				 */
2068 				if (left_edge[i] == delay_max + 1)
2069 					right_edge[i] = -(d + 1);
2070 			}
2071 			bit_chk >>= 1;
2072 		}
2073 	}
2074 
2075 	/* Reset DQ delay chains to 0 */
2076 	if (write)
2077 		scc_mgr_apply_group_dq_out1_delay(0);
2078 	else
2079 		scc_mgr_apply_group_dq_in_delay(test_bgn, 0);
2080 
2081 	*sticky_bit_chk = 0;
2082 	for (i = per_dqs - 1; i >= 0; i--) {
2083 		debug_cond(DLEVEL == 2,
2084 			   "%s:%d vfifo_center: left_edge[%u]: %d right_edge[%u]: %d\n",
2085 			   __func__, __LINE__, i, left_edge[i],
2086 			   i, right_edge[i]);
2087 
2088 		/*
2089 		 * Check for cases where we haven't found the left edge,
2090 		 * which makes our assignment of the the right edge invalid.
2091 		 * Reset it to the illegal value.
2092 		 */
2093 		if ((left_edge[i] == delay_max + 1) &&
2094 		    (right_edge[i] != delay_max + 1)) {
2095 			right_edge[i] = delay_max + 1;
2096 			debug_cond(DLEVEL == 2,
2097 				   "%s:%d vfifo_center: reset right_edge[%u]: %d\n",
2098 				   __func__, __LINE__, i, right_edge[i]);
2099 		}
2100 
2101 		/*
2102 		 * Reset sticky bit
2103 		 * READ: except for bits where we have seen both
2104 		 *       the left and right edge.
2105 		 * WRITE: except for bits where we have seen the
2106 		 *        left edge.
2107 		 */
2108 		*sticky_bit_chk <<= 1;
2109 		if (write) {
2110 			if (left_edge[i] != delay_max + 1)
2111 				*sticky_bit_chk |= 1;
2112 		} else {
2113 			if ((left_edge[i] != delay_max + 1) &&
2114 			    (right_edge[i] != delay_max + 1))
2115 				*sticky_bit_chk |= 1;
2116 		}
2117 	}
2118 
2119 
2120 }
2121 
2122 /**
2123  * search_right_edge() - Find right edge of DQ/DQS working phase
2124  * @write:		Perform read (Stage 2) or write (Stage 3) calibration
2125  * @rank_bgn:		Rank number
2126  * @write_group:	Write Group
2127  * @read_group:		Read Group
2128  * @start_dqs:		DQS start phase
2129  * @start_dqs_en:	DQS enable start phase
2130  * @sticky_bit_chk:	Resulting sticky bit mask after the test
2131  * @left_edge:		Left edge of the DQ/DQS phase
2132  * @right_edge:		Right edge of the DQ/DQS phase
2133  * @use_read_test:	Perform read test
2134  *
2135  * Find right edge of DQ/DQS working phase.
2136  */
2137 static int search_right_edge(const int write, const int rank_bgn,
2138 	const u32 write_group, const u32 read_group,
2139 	const int start_dqs, const int start_dqs_en,
2140 	u32 *sticky_bit_chk,
2141 	int *left_edge, int *right_edge, const u32 use_read_test)
2142 {
2143 	const u32 delay_max = write ? iocfg->io_out1_delay_max : iocfg->io_in_delay_max;
2144 	const u32 dqs_max = write ? iocfg->io_out1_delay_max : iocfg->dqs_in_delay_max;
2145 	const u32 per_dqs = write ? rwcfg->mem_dq_per_write_dqs :
2146 				    rwcfg->mem_dq_per_read_dqs;
2147 	u32 stop, bit_chk;
2148 	int i, d;
2149 
2150 	for (d = 0; d <= dqs_max - start_dqs; d++) {
2151 		if (write) {	/* WRITE-ONLY */
2152 			scc_mgr_apply_group_dqs_io_and_oct_out1(write_group,
2153 								d + start_dqs);
2154 		} else {	/* READ-ONLY */
2155 			scc_mgr_set_dqs_bus_in_delay(read_group, d + start_dqs);
2156 			if (iocfg->shift_dqs_en_when_shift_dqs) {
2157 				uint32_t delay = d + start_dqs_en;
2158 				if (delay > iocfg->dqs_en_delay_max)
2159 					delay = iocfg->dqs_en_delay_max;
2160 				scc_mgr_set_dqs_en_delay(read_group, delay);
2161 			}
2162 			scc_mgr_load_dqs(read_group);
2163 		}
2164 
2165 		writel(0, &sdr_scc_mgr->update);
2166 
2167 		stop = search_stop_check(write, d, rank_bgn, write_group,
2168 					 read_group, &bit_chk, sticky_bit_chk,
2169 					 use_read_test);
2170 		if (stop == 1) {
2171 			if (write && (d == 0)) {	/* WRITE-ONLY */
2172 				for (i = 0; i < rwcfg->mem_dq_per_write_dqs; i++) {
2173 					/*
2174 					 * d = 0 failed, but it passed when
2175 					 * testing the left edge, so it must be
2176 					 * marginal, set it to -1
2177 					 */
2178 					if (right_edge[i] == delay_max + 1 &&
2179 					    left_edge[i] != delay_max + 1)
2180 						right_edge[i] = -1;
2181 				}
2182 			}
2183 			break;
2184 		}
2185 
2186 		/* stop != 1 */
2187 		for (i = 0; i < per_dqs; i++) {
2188 			if (bit_chk & 1) {
2189 				/*
2190 				 * Remember a passing test as
2191 				 * the right_edge.
2192 				 */
2193 				right_edge[i] = d;
2194 			} else {
2195 				if (d != 0) {
2196 					/*
2197 					 * If a right edge has not
2198 					 * been seen yet, then a future
2199 					 * passing test will mark this
2200 					 * edge as the left edge.
2201 					 */
2202 					if (right_edge[i] == delay_max + 1)
2203 						left_edge[i] = -(d + 1);
2204 				} else {
2205 					/*
2206 					 * d = 0 failed, but it passed
2207 					 * when testing the left edge,
2208 					 * so it must be marginal, set
2209 					 * it to -1
2210 					 */
2211 					if (right_edge[i] == delay_max + 1 &&
2212 					    left_edge[i] != delay_max + 1)
2213 						right_edge[i] = -1;
2214 					/*
2215 					 * If a right edge has not been
2216 					 * seen yet, then a future
2217 					 * passing test will mark this
2218 					 * edge as the left edge.
2219 					 */
2220 					else if (right_edge[i] == delay_max + 1)
2221 						left_edge[i] = -(d + 1);
2222 				}
2223 			}
2224 
2225 			debug_cond(DLEVEL == 2, "%s:%d center[r,d=%u]: ",
2226 				   __func__, __LINE__, d);
2227 			debug_cond(DLEVEL == 2,
2228 				   "bit_chk_test=%i left_edge[%u]: %d ",
2229 				   bit_chk & 1, i, left_edge[i]);
2230 			debug_cond(DLEVEL == 2, "right_edge[%u]: %d\n", i,
2231 				   right_edge[i]);
2232 			bit_chk >>= 1;
2233 		}
2234 	}
2235 
2236 	/* Check that all bits have a window */
2237 	for (i = 0; i < per_dqs; i++) {
2238 		debug_cond(DLEVEL == 2,
2239 			   "%s:%d write_center: left_edge[%u]: %d right_edge[%u]: %d",
2240 			   __func__, __LINE__, i, left_edge[i],
2241 			   i, right_edge[i]);
2242 		if ((left_edge[i] == dqs_max + 1) ||
2243 		    (right_edge[i] == dqs_max + 1))
2244 			return i + 1;	/* FIXME: If we fail, retval > 0 */
2245 	}
2246 
2247 	return 0;
2248 }
2249 
2250 /**
2251  * get_window_mid_index() - Find the best middle setting of DQ/DQS phase
2252  * @write:		Perform read (Stage 2) or write (Stage 3) calibration
2253  * @left_edge:		Left edge of the DQ/DQS phase
2254  * @right_edge:		Right edge of the DQ/DQS phase
2255  * @mid_min:		Best DQ/DQS phase middle setting
2256  *
2257  * Find index and value of the middle of the DQ/DQS working phase.
2258  */
2259 static int get_window_mid_index(const int write, int *left_edge,
2260 				int *right_edge, int *mid_min)
2261 {
2262 	const u32 per_dqs = write ? rwcfg->mem_dq_per_write_dqs :
2263 				    rwcfg->mem_dq_per_read_dqs;
2264 	int i, mid, min_index;
2265 
2266 	/* Find middle of window for each DQ bit */
2267 	*mid_min = left_edge[0] - right_edge[0];
2268 	min_index = 0;
2269 	for (i = 1; i < per_dqs; i++) {
2270 		mid = left_edge[i] - right_edge[i];
2271 		if (mid < *mid_min) {
2272 			*mid_min = mid;
2273 			min_index = i;
2274 		}
2275 	}
2276 
2277 	/*
2278 	 * -mid_min/2 represents the amount that we need to move DQS.
2279 	 * If mid_min is odd and positive we'll need to add one to make
2280 	 * sure the rounding in further calculations is correct (always
2281 	 * bias to the right), so just add 1 for all positive values.
2282 	 */
2283 	if (*mid_min > 0)
2284 		(*mid_min)++;
2285 	*mid_min = *mid_min / 2;
2286 
2287 	debug_cond(DLEVEL == 1, "%s:%d vfifo_center: *mid_min=%d (index=%u)\n",
2288 		   __func__, __LINE__, *mid_min, min_index);
2289 	return min_index;
2290 }
2291 
2292 /**
2293  * center_dq_windows() - Center the DQ/DQS windows
2294  * @write:		Perform read (Stage 2) or write (Stage 3) calibration
2295  * @left_edge:		Left edge of the DQ/DQS phase
2296  * @right_edge:		Right edge of the DQ/DQS phase
2297  * @mid_min:		Adjusted DQ/DQS phase middle setting
2298  * @orig_mid_min:	Original DQ/DQS phase middle setting
2299  * @min_index:		DQ/DQS phase middle setting index
2300  * @test_bgn:		Rank number to begin the test
2301  * @dq_margin:		Amount of shift for the DQ
2302  * @dqs_margin:		Amount of shift for the DQS
2303  *
2304  * Align the DQ/DQS windows in each group.
2305  */
2306 static void center_dq_windows(const int write, int *left_edge, int *right_edge,
2307 			      const int mid_min, const int orig_mid_min,
2308 			      const int min_index, const int test_bgn,
2309 			      int *dq_margin, int *dqs_margin)
2310 {
2311 	const u32 delay_max = write ? iocfg->io_out1_delay_max : iocfg->io_in_delay_max;
2312 	const u32 per_dqs = write ? rwcfg->mem_dq_per_write_dqs :
2313 				    rwcfg->mem_dq_per_read_dqs;
2314 	const u32 delay_off = write ? SCC_MGR_IO_OUT1_DELAY_OFFSET :
2315 				      SCC_MGR_IO_IN_DELAY_OFFSET;
2316 	const u32 addr = SDR_PHYGRP_SCCGRP_ADDRESS | delay_off;
2317 
2318 	u32 temp_dq_io_delay1, temp_dq_io_delay2;
2319 	int shift_dq, i, p;
2320 
2321 	/* Initialize data for export structures */
2322 	*dqs_margin = delay_max + 1;
2323 	*dq_margin  = delay_max + 1;
2324 
2325 	/* add delay to bring centre of all DQ windows to the same "level" */
2326 	for (i = 0, p = test_bgn; i < per_dqs; i++, p++) {
2327 		/* Use values before divide by 2 to reduce round off error */
2328 		shift_dq = (left_edge[i] - right_edge[i] -
2329 			(left_edge[min_index] - right_edge[min_index]))/2  +
2330 			(orig_mid_min - mid_min);
2331 
2332 		debug_cond(DLEVEL == 2,
2333 			   "vfifo_center: before: shift_dq[%u]=%d\n",
2334 			   i, shift_dq);
2335 
2336 		temp_dq_io_delay1 = readl(addr + (p << 2));
2337 		temp_dq_io_delay2 = readl(addr + (i << 2));
2338 
2339 		if (shift_dq + temp_dq_io_delay1 > delay_max)
2340 			shift_dq = delay_max - temp_dq_io_delay2;
2341 		else if (shift_dq + temp_dq_io_delay1 < 0)
2342 			shift_dq = -temp_dq_io_delay1;
2343 
2344 		debug_cond(DLEVEL == 2,
2345 			   "vfifo_center: after: shift_dq[%u]=%d\n",
2346 			   i, shift_dq);
2347 
2348 		if (write)
2349 			scc_mgr_set_dq_out1_delay(i, temp_dq_io_delay1 + shift_dq);
2350 		else
2351 			scc_mgr_set_dq_in_delay(p, temp_dq_io_delay1 + shift_dq);
2352 
2353 		scc_mgr_load_dq(p);
2354 
2355 		debug_cond(DLEVEL == 2,
2356 			   "vfifo_center: margin[%u]=[%d,%d]\n", i,
2357 			   left_edge[i] - shift_dq + (-mid_min),
2358 			   right_edge[i] + shift_dq - (-mid_min));
2359 
2360 		/* To determine values for export structures */
2361 		if (left_edge[i] - shift_dq + (-mid_min) < *dq_margin)
2362 			*dq_margin = left_edge[i] - shift_dq + (-mid_min);
2363 
2364 		if (right_edge[i] + shift_dq - (-mid_min) < *dqs_margin)
2365 			*dqs_margin = right_edge[i] + shift_dq - (-mid_min);
2366 	}
2367 
2368 }
2369 
2370 /**
2371  * rw_mgr_mem_calibrate_vfifo_center() - Per-bit deskew DQ and centering
2372  * @rank_bgn:		Rank number
2373  * @rw_group:		Read/Write Group
2374  * @test_bgn:		Rank at which the test begins
2375  * @use_read_test:	Perform a read test
2376  * @update_fom:		Update FOM
2377  *
2378  * Per-bit deskew DQ and centering.
2379  */
2380 static int rw_mgr_mem_calibrate_vfifo_center(const u32 rank_bgn,
2381 			const u32 rw_group, const u32 test_bgn,
2382 			const int use_read_test, const int update_fom)
2383 {
2384 	const u32 addr =
2385 		SDR_PHYGRP_SCCGRP_ADDRESS + SCC_MGR_DQS_IN_DELAY_OFFSET +
2386 		(rw_group << 2);
2387 	/*
2388 	 * Store these as signed since there are comparisons with
2389 	 * signed numbers.
2390 	 */
2391 	uint32_t sticky_bit_chk;
2392 	int32_t left_edge[rwcfg->mem_dq_per_read_dqs];
2393 	int32_t right_edge[rwcfg->mem_dq_per_read_dqs];
2394 	int32_t orig_mid_min, mid_min;
2395 	int32_t new_dqs, start_dqs, start_dqs_en = 0, final_dqs_en;
2396 	int32_t dq_margin, dqs_margin;
2397 	int i, min_index;
2398 	int ret;
2399 
2400 	debug("%s:%d: %u %u", __func__, __LINE__, rw_group, test_bgn);
2401 
2402 	start_dqs = readl(addr);
2403 	if (iocfg->shift_dqs_en_when_shift_dqs)
2404 		start_dqs_en = readl(addr - iocfg->dqs_en_delay_offset);
2405 
2406 	/* set the left and right edge of each bit to an illegal value */
2407 	/* use (iocfg->io_in_delay_max + 1) as an illegal value */
2408 	sticky_bit_chk = 0;
2409 	for (i = 0; i < rwcfg->mem_dq_per_read_dqs; i++) {
2410 		left_edge[i]  = iocfg->io_in_delay_max + 1;
2411 		right_edge[i] = iocfg->io_in_delay_max + 1;
2412 	}
2413 
2414 	/* Search for the left edge of the window for each bit */
2415 	search_left_edge(0, rank_bgn, rw_group, rw_group, test_bgn,
2416 			 &sticky_bit_chk,
2417 			 left_edge, right_edge, use_read_test);
2418 
2419 
2420 	/* Search for the right edge of the window for each bit */
2421 	ret = search_right_edge(0, rank_bgn, rw_group, rw_group,
2422 				start_dqs, start_dqs_en,
2423 				&sticky_bit_chk,
2424 				left_edge, right_edge, use_read_test);
2425 	if (ret) {
2426 		/*
2427 		 * Restore delay chain settings before letting the loop
2428 		 * in rw_mgr_mem_calibrate_vfifo to retry different
2429 		 * dqs/ck relationships.
2430 		 */
2431 		scc_mgr_set_dqs_bus_in_delay(rw_group, start_dqs);
2432 		if (iocfg->shift_dqs_en_when_shift_dqs)
2433 			scc_mgr_set_dqs_en_delay(rw_group, start_dqs_en);
2434 
2435 		scc_mgr_load_dqs(rw_group);
2436 		writel(0, &sdr_scc_mgr->update);
2437 
2438 		debug_cond(DLEVEL == 1,
2439 			   "%s:%d vfifo_center: failed to find edge [%u]: %d %d",
2440 			   __func__, __LINE__, i, left_edge[i], right_edge[i]);
2441 		if (use_read_test) {
2442 			set_failing_group_stage(rw_group *
2443 				rwcfg->mem_dq_per_read_dqs + i,
2444 				CAL_STAGE_VFIFO,
2445 				CAL_SUBSTAGE_VFIFO_CENTER);
2446 		} else {
2447 			set_failing_group_stage(rw_group *
2448 				rwcfg->mem_dq_per_read_dqs + i,
2449 				CAL_STAGE_VFIFO_AFTER_WRITES,
2450 				CAL_SUBSTAGE_VFIFO_CENTER);
2451 		}
2452 		return -EIO;
2453 	}
2454 
2455 	min_index = get_window_mid_index(0, left_edge, right_edge, &mid_min);
2456 
2457 	/* Determine the amount we can change DQS (which is -mid_min) */
2458 	orig_mid_min = mid_min;
2459 	new_dqs = start_dqs - mid_min;
2460 	if (new_dqs > iocfg->dqs_in_delay_max)
2461 		new_dqs = iocfg->dqs_in_delay_max;
2462 	else if (new_dqs < 0)
2463 		new_dqs = 0;
2464 
2465 	mid_min = start_dqs - new_dqs;
2466 	debug_cond(DLEVEL == 1, "vfifo_center: new mid_min=%d new_dqs=%d\n",
2467 		   mid_min, new_dqs);
2468 
2469 	if (iocfg->shift_dqs_en_when_shift_dqs) {
2470 		if (start_dqs_en - mid_min > iocfg->dqs_en_delay_max)
2471 			mid_min += start_dqs_en - mid_min - iocfg->dqs_en_delay_max;
2472 		else if (start_dqs_en - mid_min < 0)
2473 			mid_min += start_dqs_en - mid_min;
2474 	}
2475 	new_dqs = start_dqs - mid_min;
2476 
2477 	debug_cond(DLEVEL == 1,
2478 		   "vfifo_center: start_dqs=%d start_dqs_en=%d new_dqs=%d mid_min=%d\n",
2479 		   start_dqs,
2480 		   iocfg->shift_dqs_en_when_shift_dqs ? start_dqs_en : -1,
2481 		   new_dqs, mid_min);
2482 
2483 	/* Add delay to bring centre of all DQ windows to the same "level". */
2484 	center_dq_windows(0, left_edge, right_edge, mid_min, orig_mid_min,
2485 			  min_index, test_bgn, &dq_margin, &dqs_margin);
2486 
2487 	/* Move DQS-en */
2488 	if (iocfg->shift_dqs_en_when_shift_dqs) {
2489 		final_dqs_en = start_dqs_en - mid_min;
2490 		scc_mgr_set_dqs_en_delay(rw_group, final_dqs_en);
2491 		scc_mgr_load_dqs(rw_group);
2492 	}
2493 
2494 	/* Move DQS */
2495 	scc_mgr_set_dqs_bus_in_delay(rw_group, new_dqs);
2496 	scc_mgr_load_dqs(rw_group);
2497 	debug_cond(DLEVEL == 2,
2498 		   "%s:%d vfifo_center: dq_margin=%d dqs_margin=%d",
2499 		   __func__, __LINE__, dq_margin, dqs_margin);
2500 
2501 	/*
2502 	 * Do not remove this line as it makes sure all of our decisions
2503 	 * have been applied. Apply the update bit.
2504 	 */
2505 	writel(0, &sdr_scc_mgr->update);
2506 
2507 	if ((dq_margin < 0) || (dqs_margin < 0))
2508 		return -EINVAL;
2509 
2510 	return 0;
2511 }
2512 
2513 /**
2514  * rw_mgr_mem_calibrate_guaranteed_write() - Perform guaranteed write into the device
2515  * @rw_group:	Read/Write Group
2516  * @phase:	DQ/DQS phase
2517  *
2518  * Because initially no communication ca be reliably performed with the memory
2519  * device, the sequencer uses a guaranteed write mechanism to write data into
2520  * the memory device.
2521  */
2522 static int rw_mgr_mem_calibrate_guaranteed_write(const u32 rw_group,
2523 						 const u32 phase)
2524 {
2525 	int ret;
2526 
2527 	/* Set a particular DQ/DQS phase. */
2528 	scc_mgr_set_dqdqs_output_phase_all_ranks(rw_group, phase);
2529 
2530 	debug_cond(DLEVEL == 1, "%s:%d guaranteed write: g=%u p=%u\n",
2531 		   __func__, __LINE__, rw_group, phase);
2532 
2533 	/*
2534 	 * Altera EMI_RM 2015.05.04 :: Figure 1-25
2535 	 * Load up the patterns used by read calibration using the
2536 	 * current DQDQS phase.
2537 	 */
2538 	rw_mgr_mem_calibrate_read_load_patterns(0, 1);
2539 
2540 	if (gbl->phy_debug_mode_flags & PHY_DEBUG_DISABLE_GUARANTEED_READ)
2541 		return 0;
2542 
2543 	/*
2544 	 * Altera EMI_RM 2015.05.04 :: Figure 1-26
2545 	 * Back-to-Back reads of the patterns used for calibration.
2546 	 */
2547 	ret = rw_mgr_mem_calibrate_read_test_patterns(0, rw_group, 1);
2548 	if (ret)
2549 		debug_cond(DLEVEL == 1,
2550 			   "%s:%d Guaranteed read test failed: g=%u p=%u\n",
2551 			   __func__, __LINE__, rw_group, phase);
2552 	return ret;
2553 }
2554 
2555 /**
2556  * rw_mgr_mem_calibrate_dqs_enable_calibration() - DQS Enable Calibration
2557  * @rw_group:	Read/Write Group
2558  * @test_bgn:	Rank at which the test begins
2559  *
2560  * DQS enable calibration ensures reliable capture of the DQ signal without
2561  * glitches on the DQS line.
2562  */
2563 static int rw_mgr_mem_calibrate_dqs_enable_calibration(const u32 rw_group,
2564 						       const u32 test_bgn)
2565 {
2566 	/*
2567 	 * Altera EMI_RM 2015.05.04 :: Figure 1-27
2568 	 * DQS and DQS Eanble Signal Relationships.
2569 	 */
2570 
2571 	/* We start at zero, so have one less dq to devide among */
2572 	const u32 delay_step = iocfg->io_in_delay_max /
2573 			       (rwcfg->mem_dq_per_read_dqs - 1);
2574 	int ret;
2575 	u32 i, p, d, r;
2576 
2577 	debug("%s:%d (%u,%u)\n", __func__, __LINE__, rw_group, test_bgn);
2578 
2579 	/* Try different dq_in_delays since the DQ path is shorter than DQS. */
2580 	for (r = 0; r < rwcfg->mem_number_of_ranks;
2581 	     r += NUM_RANKS_PER_SHADOW_REG) {
2582 		for (i = 0, p = test_bgn, d = 0;
2583 		     i < rwcfg->mem_dq_per_read_dqs;
2584 		     i++, p++, d += delay_step) {
2585 			debug_cond(DLEVEL == 1,
2586 				   "%s:%d: g=%u r=%u i=%u p=%u d=%u\n",
2587 				   __func__, __LINE__, rw_group, r, i, p, d);
2588 
2589 			scc_mgr_set_dq_in_delay(p, d);
2590 			scc_mgr_load_dq(p);
2591 		}
2592 
2593 		writel(0, &sdr_scc_mgr->update);
2594 	}
2595 
2596 	/*
2597 	 * Try rw_mgr_mem_calibrate_vfifo_find_dqs_en_phase across different
2598 	 * dq_in_delay values
2599 	 */
2600 	ret = rw_mgr_mem_calibrate_vfifo_find_dqs_en_phase(rw_group);
2601 
2602 	debug_cond(DLEVEL == 1,
2603 		   "%s:%d: g=%u found=%u; Reseting delay chain to zero\n",
2604 		   __func__, __LINE__, rw_group, !ret);
2605 
2606 	for (r = 0; r < rwcfg->mem_number_of_ranks;
2607 	     r += NUM_RANKS_PER_SHADOW_REG) {
2608 		scc_mgr_apply_group_dq_in_delay(test_bgn, 0);
2609 		writel(0, &sdr_scc_mgr->update);
2610 	}
2611 
2612 	return ret;
2613 }
2614 
2615 /**
2616  * rw_mgr_mem_calibrate_dq_dqs_centering() - Centering DQ/DQS
2617  * @rw_group:		Read/Write Group
2618  * @test_bgn:		Rank at which the test begins
2619  * @use_read_test:	Perform a read test
2620  * @update_fom:		Update FOM
2621  *
2622  * The centerin DQ/DQS stage attempts to align DQ and DQS signals on reads
2623  * within a group.
2624  */
2625 static int
2626 rw_mgr_mem_calibrate_dq_dqs_centering(const u32 rw_group, const u32 test_bgn,
2627 				      const int use_read_test,
2628 				      const int update_fom)
2629 
2630 {
2631 	int ret, grp_calibrated;
2632 	u32 rank_bgn, sr;
2633 
2634 	/*
2635 	 * Altera EMI_RM 2015.05.04 :: Figure 1-28
2636 	 * Read per-bit deskew can be done on a per shadow register basis.
2637 	 */
2638 	grp_calibrated = 1;
2639 	for (rank_bgn = 0, sr = 0;
2640 	     rank_bgn < rwcfg->mem_number_of_ranks;
2641 	     rank_bgn += NUM_RANKS_PER_SHADOW_REG, sr++) {
2642 		ret = rw_mgr_mem_calibrate_vfifo_center(rank_bgn, rw_group,
2643 							test_bgn,
2644 							use_read_test,
2645 							update_fom);
2646 		if (!ret)
2647 			continue;
2648 
2649 		grp_calibrated = 0;
2650 	}
2651 
2652 	if (!grp_calibrated)
2653 		return -EIO;
2654 
2655 	return 0;
2656 }
2657 
2658 /**
2659  * rw_mgr_mem_calibrate_vfifo() - Calibrate the read valid prediction FIFO
2660  * @rw_group:		Read/Write Group
2661  * @test_bgn:		Rank at which the test begins
2662  *
2663  * Stage 1: Calibrate the read valid prediction FIFO.
2664  *
2665  * This function implements UniPHY calibration Stage 1, as explained in
2666  * detail in Altera EMI_RM 2015.05.04 , "UniPHY Calibration Stages".
2667  *
2668  * - read valid prediction will consist of finding:
2669  *   - DQS enable phase and DQS enable delay (DQS Enable Calibration)
2670  *   - DQS input phase  and DQS input delay (DQ/DQS Centering)
2671  *  - we also do a per-bit deskew on the DQ lines.
2672  */
2673 static int rw_mgr_mem_calibrate_vfifo(const u32 rw_group, const u32 test_bgn)
2674 {
2675 	uint32_t p, d;
2676 	uint32_t dtaps_per_ptap;
2677 	uint32_t failed_substage;
2678 
2679 	int ret;
2680 
2681 	debug("%s:%d: %u %u\n", __func__, __LINE__, rw_group, test_bgn);
2682 
2683 	/* Update info for sims */
2684 	reg_file_set_group(rw_group);
2685 	reg_file_set_stage(CAL_STAGE_VFIFO);
2686 	reg_file_set_sub_stage(CAL_SUBSTAGE_GUARANTEED_READ);
2687 
2688 	failed_substage = CAL_SUBSTAGE_GUARANTEED_READ;
2689 
2690 	/* USER Determine number of delay taps for each phase tap. */
2691 	dtaps_per_ptap = DIV_ROUND_UP(iocfg->delay_per_opa_tap,
2692 				      iocfg->delay_per_dqs_en_dchain_tap) - 1;
2693 
2694 	for (d = 0; d <= dtaps_per_ptap; d += 2) {
2695 		/*
2696 		 * In RLDRAMX we may be messing the delay of pins in
2697 		 * the same write rw_group but outside of the current read
2698 		 * the rw_group, but that's ok because we haven't calibrated
2699 		 * output side yet.
2700 		 */
2701 		if (d > 0) {
2702 			scc_mgr_apply_group_all_out_delay_add_all_ranks(
2703 								rw_group, d);
2704 		}
2705 
2706 		for (p = 0; p <= iocfg->dqdqs_out_phase_max; p++) {
2707 			/* 1) Guaranteed Write */
2708 			ret = rw_mgr_mem_calibrate_guaranteed_write(rw_group, p);
2709 			if (ret)
2710 				break;
2711 
2712 			/* 2) DQS Enable Calibration */
2713 			ret = rw_mgr_mem_calibrate_dqs_enable_calibration(rw_group,
2714 									  test_bgn);
2715 			if (ret) {
2716 				failed_substage = CAL_SUBSTAGE_DQS_EN_PHASE;
2717 				continue;
2718 			}
2719 
2720 			/* 3) Centering DQ/DQS */
2721 			/*
2722 			 * If doing read after write calibration, do not update
2723 			 * FOM now. Do it then.
2724 			 */
2725 			ret = rw_mgr_mem_calibrate_dq_dqs_centering(rw_group,
2726 								test_bgn, 1, 0);
2727 			if (ret) {
2728 				failed_substage = CAL_SUBSTAGE_VFIFO_CENTER;
2729 				continue;
2730 			}
2731 
2732 			/* All done. */
2733 			goto cal_done_ok;
2734 		}
2735 	}
2736 
2737 	/* Calibration Stage 1 failed. */
2738 	set_failing_group_stage(rw_group, CAL_STAGE_VFIFO, failed_substage);
2739 	return 0;
2740 
2741 	/* Calibration Stage 1 completed OK. */
2742 cal_done_ok:
2743 	/*
2744 	 * Reset the delay chains back to zero if they have moved > 1
2745 	 * (check for > 1 because loop will increase d even when pass in
2746 	 * first case).
2747 	 */
2748 	if (d > 2)
2749 		scc_mgr_zero_group(rw_group, 1);
2750 
2751 	return 1;
2752 }
2753 
2754 /**
2755  * rw_mgr_mem_calibrate_vfifo_end() - DQ/DQS Centering.
2756  * @rw_group:		Read/Write Group
2757  * @test_bgn:		Rank at which the test begins
2758  *
2759  * Stage 3: DQ/DQS Centering.
2760  *
2761  * This function implements UniPHY calibration Stage 3, as explained in
2762  * detail in Altera EMI_RM 2015.05.04 , "UniPHY Calibration Stages".
2763  */
2764 static int rw_mgr_mem_calibrate_vfifo_end(const u32 rw_group,
2765 					  const u32 test_bgn)
2766 {
2767 	int ret;
2768 
2769 	debug("%s:%d %u %u", __func__, __LINE__, rw_group, test_bgn);
2770 
2771 	/* Update info for sims. */
2772 	reg_file_set_group(rw_group);
2773 	reg_file_set_stage(CAL_STAGE_VFIFO_AFTER_WRITES);
2774 	reg_file_set_sub_stage(CAL_SUBSTAGE_VFIFO_CENTER);
2775 
2776 	ret = rw_mgr_mem_calibrate_dq_dqs_centering(rw_group, test_bgn, 0, 1);
2777 	if (ret)
2778 		set_failing_group_stage(rw_group,
2779 					CAL_STAGE_VFIFO_AFTER_WRITES,
2780 					CAL_SUBSTAGE_VFIFO_CENTER);
2781 	return ret;
2782 }
2783 
2784 /**
2785  * rw_mgr_mem_calibrate_lfifo() - Minimize latency
2786  *
2787  * Stage 4: Minimize latency.
2788  *
2789  * This function implements UniPHY calibration Stage 4, as explained in
2790  * detail in Altera EMI_RM 2015.05.04 , "UniPHY Calibration Stages".
2791  * Calibrate LFIFO to find smallest read latency.
2792  */
2793 static uint32_t rw_mgr_mem_calibrate_lfifo(void)
2794 {
2795 	int found_one = 0;
2796 
2797 	debug("%s:%d\n", __func__, __LINE__);
2798 
2799 	/* Update info for sims. */
2800 	reg_file_set_stage(CAL_STAGE_LFIFO);
2801 	reg_file_set_sub_stage(CAL_SUBSTAGE_READ_LATENCY);
2802 
2803 	/* Load up the patterns used by read calibration for all ranks */
2804 	rw_mgr_mem_calibrate_read_load_patterns(0, 1);
2805 
2806 	do {
2807 		writel(gbl->curr_read_lat, &phy_mgr_cfg->phy_rlat);
2808 		debug_cond(DLEVEL == 2, "%s:%d lfifo: read_lat=%u",
2809 			   __func__, __LINE__, gbl->curr_read_lat);
2810 
2811 		if (!rw_mgr_mem_calibrate_read_test_all_ranks(0, NUM_READ_TESTS,
2812 							      PASS_ALL_BITS, 1))
2813 			break;
2814 
2815 		found_one = 1;
2816 		/*
2817 		 * Reduce read latency and see if things are
2818 		 * working correctly.
2819 		 */
2820 		gbl->curr_read_lat--;
2821 	} while (gbl->curr_read_lat > 0);
2822 
2823 	/* Reset the fifos to get pointers to known state. */
2824 	writel(0, &phy_mgr_cmd->fifo_reset);
2825 
2826 	if (found_one) {
2827 		/* Add a fudge factor to the read latency that was determined */
2828 		gbl->curr_read_lat += 2;
2829 		writel(gbl->curr_read_lat, &phy_mgr_cfg->phy_rlat);
2830 		debug_cond(DLEVEL == 2,
2831 			   "%s:%d lfifo: success: using read_lat=%u\n",
2832 			   __func__, __LINE__, gbl->curr_read_lat);
2833 	} else {
2834 		set_failing_group_stage(0xff, CAL_STAGE_LFIFO,
2835 					CAL_SUBSTAGE_READ_LATENCY);
2836 
2837 		debug_cond(DLEVEL == 2,
2838 			   "%s:%d lfifo: failed at initial read_lat=%u\n",
2839 			   __func__, __LINE__, gbl->curr_read_lat);
2840 	}
2841 
2842 	return found_one;
2843 }
2844 
2845 /**
2846  * search_window() - Search for the/part of the window with DM/DQS shift
2847  * @search_dm:		If 1, search for the DM shift, if 0, search for DQS shift
2848  * @rank_bgn:		Rank number
2849  * @write_group:	Write Group
2850  * @bgn_curr:		Current window begin
2851  * @end_curr:		Current window end
2852  * @bgn_best:		Current best window begin
2853  * @end_best:		Current best window end
2854  * @win_best:		Size of the best window
2855  * @new_dqs:		New DQS value (only applicable if search_dm = 0).
2856  *
2857  * Search for the/part of the window with DM/DQS shift.
2858  */
2859 static void search_window(const int search_dm,
2860 			  const u32 rank_bgn, const u32 write_group,
2861 			  int *bgn_curr, int *end_curr, int *bgn_best,
2862 			  int *end_best, int *win_best, int new_dqs)
2863 {
2864 	u32 bit_chk;
2865 	const int max = iocfg->io_out1_delay_max - new_dqs;
2866 	int d, di;
2867 
2868 	/* Search for the/part of the window with DM/DQS shift. */
2869 	for (di = max; di >= 0; di -= DELTA_D) {
2870 		if (search_dm) {
2871 			d = di;
2872 			scc_mgr_apply_group_dm_out1_delay(d);
2873 		} else {
2874 			/* For DQS, we go from 0...max */
2875 			d = max - di;
2876 			/*
2877 			 * Note: This only shifts DQS, so are we limiting ourselve to
2878 			 * width of DQ unnecessarily.
2879 			 */
2880 			scc_mgr_apply_group_dqs_io_and_oct_out1(write_group,
2881 								d + new_dqs);
2882 		}
2883 
2884 		writel(0, &sdr_scc_mgr->update);
2885 
2886 		if (rw_mgr_mem_calibrate_write_test(rank_bgn, write_group, 1,
2887 						    PASS_ALL_BITS, &bit_chk,
2888 						    0)) {
2889 			/* Set current end of the window. */
2890 			*end_curr = search_dm ? -d : d;
2891 
2892 			/*
2893 			 * If a starting edge of our window has not been seen
2894 			 * this is our current start of the DM window.
2895 			 */
2896 			if (*bgn_curr == iocfg->io_out1_delay_max + 1)
2897 				*bgn_curr = search_dm ? -d : d;
2898 
2899 			/*
2900 			 * If current window is bigger than best seen.
2901 			 * Set best seen to be current window.
2902 			 */
2903 			if ((*end_curr - *bgn_curr + 1) > *win_best) {
2904 				*win_best = *end_curr - *bgn_curr + 1;
2905 				*bgn_best = *bgn_curr;
2906 				*end_best = *end_curr;
2907 			}
2908 		} else {
2909 			/* We just saw a failing test. Reset temp edge. */
2910 			*bgn_curr = iocfg->io_out1_delay_max + 1;
2911 			*end_curr = iocfg->io_out1_delay_max + 1;
2912 
2913 			/* Early exit is only applicable to DQS. */
2914 			if (search_dm)
2915 				continue;
2916 
2917 			/*
2918 			 * Early exit optimization: if the remaining delay
2919 			 * chain space is less than already seen largest
2920 			 * window we can exit.
2921 			 */
2922 			if (*win_best - 1 > iocfg->io_out1_delay_max - new_dqs - d)
2923 				break;
2924 		}
2925 	}
2926 }
2927 
2928 /*
2929  * rw_mgr_mem_calibrate_writes_center() - Center all windows
2930  * @rank_bgn:		Rank number
2931  * @write_group:	Write group
2932  * @test_bgn:		Rank at which the test begins
2933  *
2934  * Center all windows. Do per-bit-deskew to possibly increase size of
2935  * certain windows.
2936  */
2937 static int
2938 rw_mgr_mem_calibrate_writes_center(const u32 rank_bgn, const u32 write_group,
2939 				   const u32 test_bgn)
2940 {
2941 	int i;
2942 	u32 sticky_bit_chk;
2943 	u32 min_index;
2944 	int left_edge[rwcfg->mem_dq_per_write_dqs];
2945 	int right_edge[rwcfg->mem_dq_per_write_dqs];
2946 	int mid;
2947 	int mid_min, orig_mid_min;
2948 	int new_dqs, start_dqs;
2949 	int dq_margin, dqs_margin, dm_margin;
2950 	int bgn_curr = iocfg->io_out1_delay_max + 1;
2951 	int end_curr = iocfg->io_out1_delay_max + 1;
2952 	int bgn_best = iocfg->io_out1_delay_max + 1;
2953 	int end_best = iocfg->io_out1_delay_max + 1;
2954 	int win_best = 0;
2955 
2956 	int ret;
2957 
2958 	debug("%s:%d %u %u", __func__, __LINE__, write_group, test_bgn);
2959 
2960 	dm_margin = 0;
2961 
2962 	start_dqs = readl((SDR_PHYGRP_SCCGRP_ADDRESS |
2963 			  SCC_MGR_IO_OUT1_DELAY_OFFSET) +
2964 			  (rwcfg->mem_dq_per_write_dqs << 2));
2965 
2966 	/* Per-bit deskew. */
2967 
2968 	/*
2969 	 * Set the left and right edge of each bit to an illegal value.
2970 	 * Use (iocfg->io_out1_delay_max + 1) as an illegal value.
2971 	 */
2972 	sticky_bit_chk = 0;
2973 	for (i = 0; i < rwcfg->mem_dq_per_write_dqs; i++) {
2974 		left_edge[i]  = iocfg->io_out1_delay_max + 1;
2975 		right_edge[i] = iocfg->io_out1_delay_max + 1;
2976 	}
2977 
2978 	/* Search for the left edge of the window for each bit. */
2979 	search_left_edge(1, rank_bgn, write_group, 0, test_bgn,
2980 			 &sticky_bit_chk,
2981 			 left_edge, right_edge, 0);
2982 
2983 	/* Search for the right edge of the window for each bit. */
2984 	ret = search_right_edge(1, rank_bgn, write_group, 0,
2985 				start_dqs, 0,
2986 				&sticky_bit_chk,
2987 				left_edge, right_edge, 0);
2988 	if (ret) {
2989 		set_failing_group_stage(test_bgn + ret - 1, CAL_STAGE_WRITES,
2990 					CAL_SUBSTAGE_WRITES_CENTER);
2991 		return -EINVAL;
2992 	}
2993 
2994 	min_index = get_window_mid_index(1, left_edge, right_edge, &mid_min);
2995 
2996 	/* Determine the amount we can change DQS (which is -mid_min). */
2997 	orig_mid_min = mid_min;
2998 	new_dqs = start_dqs;
2999 	mid_min = 0;
3000 	debug_cond(DLEVEL == 1,
3001 		   "%s:%d write_center: start_dqs=%d new_dqs=%d mid_min=%d\n",
3002 		   __func__, __LINE__, start_dqs, new_dqs, mid_min);
3003 
3004 	/* Add delay to bring centre of all DQ windows to the same "level". */
3005 	center_dq_windows(1, left_edge, right_edge, mid_min, orig_mid_min,
3006 			  min_index, 0, &dq_margin, &dqs_margin);
3007 
3008 	/* Move DQS */
3009 	scc_mgr_apply_group_dqs_io_and_oct_out1(write_group, new_dqs);
3010 	writel(0, &sdr_scc_mgr->update);
3011 
3012 	/* Centre DM */
3013 	debug_cond(DLEVEL == 2, "%s:%d write_center: DM\n", __func__, __LINE__);
3014 
3015 	/*
3016 	 * Set the left and right edge of each bit to an illegal value.
3017 	 * Use (iocfg->io_out1_delay_max + 1) as an illegal value.
3018 	 */
3019 	left_edge[0]  = iocfg->io_out1_delay_max + 1;
3020 	right_edge[0] = iocfg->io_out1_delay_max + 1;
3021 
3022 	/* Search for the/part of the window with DM shift. */
3023 	search_window(1, rank_bgn, write_group, &bgn_curr, &end_curr,
3024 		      &bgn_best, &end_best, &win_best, 0);
3025 
3026 	/* Reset DM delay chains to 0. */
3027 	scc_mgr_apply_group_dm_out1_delay(0);
3028 
3029 	/*
3030 	 * Check to see if the current window nudges up aganist 0 delay.
3031 	 * If so we need to continue the search by shifting DQS otherwise DQS
3032 	 * search begins as a new search.
3033 	 */
3034 	if (end_curr != 0) {
3035 		bgn_curr = iocfg->io_out1_delay_max + 1;
3036 		end_curr = iocfg->io_out1_delay_max + 1;
3037 	}
3038 
3039 	/* Search for the/part of the window with DQS shifts. */
3040 	search_window(0, rank_bgn, write_group, &bgn_curr, &end_curr,
3041 		      &bgn_best, &end_best, &win_best, new_dqs);
3042 
3043 	/* Assign left and right edge for cal and reporting. */
3044 	left_edge[0] = -1 * bgn_best;
3045 	right_edge[0] = end_best;
3046 
3047 	debug_cond(DLEVEL == 2, "%s:%d dm_calib: left=%d right=%d\n",
3048 		   __func__, __LINE__, left_edge[0], right_edge[0]);
3049 
3050 	/* Move DQS (back to orig). */
3051 	scc_mgr_apply_group_dqs_io_and_oct_out1(write_group, new_dqs);
3052 
3053 	/* Move DM */
3054 
3055 	/* Find middle of window for the DM bit. */
3056 	mid = (left_edge[0] - right_edge[0]) / 2;
3057 
3058 	/* Only move right, since we are not moving DQS/DQ. */
3059 	if (mid < 0)
3060 		mid = 0;
3061 
3062 	/* dm_marign should fail if we never find a window. */
3063 	if (win_best == 0)
3064 		dm_margin = -1;
3065 	else
3066 		dm_margin = left_edge[0] - mid;
3067 
3068 	scc_mgr_apply_group_dm_out1_delay(mid);
3069 	writel(0, &sdr_scc_mgr->update);
3070 
3071 	debug_cond(DLEVEL == 2,
3072 		   "%s:%d dm_calib: left=%d right=%d mid=%d dm_margin=%d\n",
3073 		   __func__, __LINE__, left_edge[0], right_edge[0],
3074 		   mid, dm_margin);
3075 	/* Export values. */
3076 	gbl->fom_out += dq_margin + dqs_margin;
3077 
3078 	debug_cond(DLEVEL == 2,
3079 		   "%s:%d write_center: dq_margin=%d dqs_margin=%d dm_margin=%d\n",
3080 		   __func__, __LINE__, dq_margin, dqs_margin, dm_margin);
3081 
3082 	/*
3083 	 * Do not remove this line as it makes sure all of our
3084 	 * decisions have been applied.
3085 	 */
3086 	writel(0, &sdr_scc_mgr->update);
3087 
3088 	if ((dq_margin < 0) || (dqs_margin < 0) || (dm_margin < 0))
3089 		return -EINVAL;
3090 
3091 	return 0;
3092 }
3093 
3094 /**
3095  * rw_mgr_mem_calibrate_writes() - Write Calibration Part One
3096  * @rank_bgn:		Rank number
3097  * @group:		Read/Write Group
3098  * @test_bgn:		Rank at which the test begins
3099  *
3100  * Stage 2: Write Calibration Part One.
3101  *
3102  * This function implements UniPHY calibration Stage 2, as explained in
3103  * detail in Altera EMI_RM 2015.05.04 , "UniPHY Calibration Stages".
3104  */
3105 static int rw_mgr_mem_calibrate_writes(const u32 rank_bgn, const u32 group,
3106 				       const u32 test_bgn)
3107 {
3108 	int ret;
3109 
3110 	/* Update info for sims */
3111 	debug("%s:%d %u %u\n", __func__, __LINE__, group, test_bgn);
3112 
3113 	reg_file_set_group(group);
3114 	reg_file_set_stage(CAL_STAGE_WRITES);
3115 	reg_file_set_sub_stage(CAL_SUBSTAGE_WRITES_CENTER);
3116 
3117 	ret = rw_mgr_mem_calibrate_writes_center(rank_bgn, group, test_bgn);
3118 	if (ret)
3119 		set_failing_group_stage(group, CAL_STAGE_WRITES,
3120 					CAL_SUBSTAGE_WRITES_CENTER);
3121 
3122 	return ret;
3123 }
3124 
3125 /**
3126  * mem_precharge_and_activate() - Precharge all banks and activate
3127  *
3128  * Precharge all banks and activate row 0 in bank "000..." and bank "111...".
3129  */
3130 static void mem_precharge_and_activate(void)
3131 {
3132 	int r;
3133 
3134 	for (r = 0; r < rwcfg->mem_number_of_ranks; r++) {
3135 		/* Set rank. */
3136 		set_rank_and_odt_mask(r, RW_MGR_ODT_MODE_OFF);
3137 
3138 		/* Precharge all banks. */
3139 		writel(rwcfg->precharge_all, SDR_PHYGRP_RWMGRGRP_ADDRESS |
3140 					     RW_MGR_RUN_SINGLE_GROUP_OFFSET);
3141 
3142 		writel(0x0F, &sdr_rw_load_mgr_regs->load_cntr0);
3143 		writel(rwcfg->activate_0_and_1_wait1,
3144 			&sdr_rw_load_jump_mgr_regs->load_jump_add0);
3145 
3146 		writel(0x0F, &sdr_rw_load_mgr_regs->load_cntr1);
3147 		writel(rwcfg->activate_0_and_1_wait2,
3148 			&sdr_rw_load_jump_mgr_regs->load_jump_add1);
3149 
3150 		/* Activate rows. */
3151 		writel(rwcfg->activate_0_and_1, SDR_PHYGRP_RWMGRGRP_ADDRESS |
3152 						RW_MGR_RUN_SINGLE_GROUP_OFFSET);
3153 	}
3154 }
3155 
3156 /**
3157  * mem_init_latency() - Configure memory RLAT and WLAT settings
3158  *
3159  * Configure memory RLAT and WLAT parameters.
3160  */
3161 static void mem_init_latency(void)
3162 {
3163 	/*
3164 	 * For AV/CV, LFIFO is hardened and always runs at full rate
3165 	 * so max latency in AFI clocks, used here, is correspondingly
3166 	 * smaller.
3167 	 */
3168 	const u32 max_latency = (1 << MAX_LATENCY_COUNT_WIDTH) - 1;
3169 	u32 rlat, wlat;
3170 
3171 	debug("%s:%d\n", __func__, __LINE__);
3172 
3173 	/*
3174 	 * Read in write latency.
3175 	 * WL for Hard PHY does not include additive latency.
3176 	 */
3177 	wlat = readl(&data_mgr->t_wl_add);
3178 	wlat += readl(&data_mgr->mem_t_add);
3179 
3180 	gbl->rw_wl_nop_cycles = wlat - 1;
3181 
3182 	/* Read in readl latency. */
3183 	rlat = readl(&data_mgr->t_rl_add);
3184 
3185 	/* Set a pretty high read latency initially. */
3186 	gbl->curr_read_lat = rlat + 16;
3187 	if (gbl->curr_read_lat > max_latency)
3188 		gbl->curr_read_lat = max_latency;
3189 
3190 	writel(gbl->curr_read_lat, &phy_mgr_cfg->phy_rlat);
3191 
3192 	/* Advertise write latency. */
3193 	writel(wlat, &phy_mgr_cfg->afi_wlat);
3194 }
3195 
3196 /**
3197  * @mem_skip_calibrate() - Set VFIFO and LFIFO to instant-on settings
3198  *
3199  * Set VFIFO and LFIFO to instant-on settings in skip calibration mode.
3200  */
3201 static void mem_skip_calibrate(void)
3202 {
3203 	uint32_t vfifo_offset;
3204 	uint32_t i, j, r;
3205 
3206 	debug("%s:%d\n", __func__, __LINE__);
3207 	/* Need to update every shadow register set used by the interface */
3208 	for (r = 0; r < rwcfg->mem_number_of_ranks;
3209 	     r += NUM_RANKS_PER_SHADOW_REG) {
3210 		/*
3211 		 * Set output phase alignment settings appropriate for
3212 		 * skip calibration.
3213 		 */
3214 		for (i = 0; i < rwcfg->mem_if_read_dqs_width; i++) {
3215 			scc_mgr_set_dqs_en_phase(i, 0);
3216 			if (iocfg->dll_chain_length == 6)
3217 				scc_mgr_set_dqdqs_output_phase(i, 6);
3218 			else
3219 				scc_mgr_set_dqdqs_output_phase(i, 7);
3220 			/*
3221 			 * Case:33398
3222 			 *
3223 			 * Write data arrives to the I/O two cycles before write
3224 			 * latency is reached (720 deg).
3225 			 *   -> due to bit-slip in a/c bus
3226 			 *   -> to allow board skew where dqs is longer than ck
3227 			 *      -> how often can this happen!?
3228 			 *      -> can claim back some ptaps for high freq
3229 			 *       support if we can relax this, but i digress...
3230 			 *
3231 			 * The write_clk leads mem_ck by 90 deg
3232 			 * The minimum ptap of the OPA is 180 deg
3233 			 * Each ptap has (360 / IO_DLL_CHAIN_LENGH) deg of delay
3234 			 * The write_clk is always delayed by 2 ptaps
3235 			 *
3236 			 * Hence, to make DQS aligned to CK, we need to delay
3237 			 * DQS by:
3238 			 *    (720 - 90 - 180 - 2 * (360 / iocfg->dll_chain_length))
3239 			 *
3240 			 * Dividing the above by (360 / iocfg->dll_chain_length)
3241 			 * gives us the number of ptaps, which simplies to:
3242 			 *
3243 			 *    (1.25 * iocfg->dll_chain_length - 2)
3244 			 */
3245 			scc_mgr_set_dqdqs_output_phase(i,
3246 					1.25 * iocfg->dll_chain_length - 2);
3247 		}
3248 		writel(0xff, &sdr_scc_mgr->dqs_ena);
3249 		writel(0xff, &sdr_scc_mgr->dqs_io_ena);
3250 
3251 		for (i = 0; i < rwcfg->mem_if_write_dqs_width; i++) {
3252 			writel(i, SDR_PHYGRP_SCCGRP_ADDRESS |
3253 				  SCC_MGR_GROUP_COUNTER_OFFSET);
3254 		}
3255 		writel(0xff, &sdr_scc_mgr->dq_ena);
3256 		writel(0xff, &sdr_scc_mgr->dm_ena);
3257 		writel(0, &sdr_scc_mgr->update);
3258 	}
3259 
3260 	/* Compensate for simulation model behaviour */
3261 	for (i = 0; i < rwcfg->mem_if_read_dqs_width; i++) {
3262 		scc_mgr_set_dqs_bus_in_delay(i, 10);
3263 		scc_mgr_load_dqs(i);
3264 	}
3265 	writel(0, &sdr_scc_mgr->update);
3266 
3267 	/*
3268 	 * ArriaV has hard FIFOs that can only be initialized by incrementing
3269 	 * in sequencer.
3270 	 */
3271 	vfifo_offset = CALIB_VFIFO_OFFSET;
3272 	for (j = 0; j < vfifo_offset; j++)
3273 		writel(0xff, &phy_mgr_cmd->inc_vfifo_hard_phy);
3274 	writel(0, &phy_mgr_cmd->fifo_reset);
3275 
3276 	/*
3277 	 * For Arria V and Cyclone V with hard LFIFO, we get the skip-cal
3278 	 * setting from generation-time constant.
3279 	 */
3280 	gbl->curr_read_lat = CALIB_LFIFO_OFFSET;
3281 	writel(gbl->curr_read_lat, &phy_mgr_cfg->phy_rlat);
3282 }
3283 
3284 /**
3285  * mem_calibrate() - Memory calibration entry point.
3286  *
3287  * Perform memory calibration.
3288  */
3289 static uint32_t mem_calibrate(void)
3290 {
3291 	uint32_t i;
3292 	uint32_t rank_bgn, sr;
3293 	uint32_t write_group, write_test_bgn;
3294 	uint32_t read_group, read_test_bgn;
3295 	uint32_t run_groups, current_run;
3296 	uint32_t failing_groups = 0;
3297 	uint32_t group_failed = 0;
3298 
3299 	const u32 rwdqs_ratio = rwcfg->mem_if_read_dqs_width /
3300 				rwcfg->mem_if_write_dqs_width;
3301 
3302 	debug("%s:%d\n", __func__, __LINE__);
3303 
3304 	/* Initialize the data settings */
3305 	gbl->error_substage = CAL_SUBSTAGE_NIL;
3306 	gbl->error_stage = CAL_STAGE_NIL;
3307 	gbl->error_group = 0xff;
3308 	gbl->fom_in = 0;
3309 	gbl->fom_out = 0;
3310 
3311 	/* Initialize WLAT and RLAT. */
3312 	mem_init_latency();
3313 
3314 	/* Initialize bit slips. */
3315 	mem_precharge_and_activate();
3316 
3317 	for (i = 0; i < rwcfg->mem_if_read_dqs_width; i++) {
3318 		writel(i, SDR_PHYGRP_SCCGRP_ADDRESS |
3319 			  SCC_MGR_GROUP_COUNTER_OFFSET);
3320 		/* Only needed once to set all groups, pins, DQ, DQS, DM. */
3321 		if (i == 0)
3322 			scc_mgr_set_hhp_extras();
3323 
3324 		scc_set_bypass_mode(i);
3325 	}
3326 
3327 	/* Calibration is skipped. */
3328 	if ((dyn_calib_steps & CALIB_SKIP_ALL) == CALIB_SKIP_ALL) {
3329 		/*
3330 		 * Set VFIFO and LFIFO to instant-on settings in skip
3331 		 * calibration mode.
3332 		 */
3333 		mem_skip_calibrate();
3334 
3335 		/*
3336 		 * Do not remove this line as it makes sure all of our
3337 		 * decisions have been applied.
3338 		 */
3339 		writel(0, &sdr_scc_mgr->update);
3340 		return 1;
3341 	}
3342 
3343 	/* Calibration is not skipped. */
3344 	for (i = 0; i < NUM_CALIB_REPEAT; i++) {
3345 		/*
3346 		 * Zero all delay chain/phase settings for all
3347 		 * groups and all shadow register sets.
3348 		 */
3349 		scc_mgr_zero_all();
3350 
3351 		run_groups = ~0;
3352 
3353 		for (write_group = 0, write_test_bgn = 0; write_group
3354 			< rwcfg->mem_if_write_dqs_width; write_group++,
3355 			write_test_bgn += rwcfg->mem_dq_per_write_dqs) {
3356 
3357 			/* Initialize the group failure */
3358 			group_failed = 0;
3359 
3360 			current_run = run_groups & ((1 <<
3361 				RW_MGR_NUM_DQS_PER_WRITE_GROUP) - 1);
3362 			run_groups = run_groups >>
3363 				RW_MGR_NUM_DQS_PER_WRITE_GROUP;
3364 
3365 			if (current_run == 0)
3366 				continue;
3367 
3368 			writel(write_group, SDR_PHYGRP_SCCGRP_ADDRESS |
3369 					    SCC_MGR_GROUP_COUNTER_OFFSET);
3370 			scc_mgr_zero_group(write_group, 0);
3371 
3372 			for (read_group = write_group * rwdqs_ratio,
3373 			     read_test_bgn = 0;
3374 			     read_group < (write_group + 1) * rwdqs_ratio;
3375 			     read_group++,
3376 			     read_test_bgn += rwcfg->mem_dq_per_read_dqs) {
3377 				if (STATIC_CALIB_STEPS & CALIB_SKIP_VFIFO)
3378 					continue;
3379 
3380 				/* Calibrate the VFIFO */
3381 				if (rw_mgr_mem_calibrate_vfifo(read_group,
3382 							       read_test_bgn))
3383 					continue;
3384 
3385 				if (!(gbl->phy_debug_mode_flags & PHY_DEBUG_SWEEP_ALL_GROUPS))
3386 					return 0;
3387 
3388 				/* The group failed, we're done. */
3389 				goto grp_failed;
3390 			}
3391 
3392 			/* Calibrate the output side */
3393 			for (rank_bgn = 0, sr = 0;
3394 			     rank_bgn < rwcfg->mem_number_of_ranks;
3395 			     rank_bgn += NUM_RANKS_PER_SHADOW_REG, sr++) {
3396 				if (STATIC_CALIB_STEPS & CALIB_SKIP_WRITES)
3397 					continue;
3398 
3399 				/* Not needed in quick mode! */
3400 				if (STATIC_CALIB_STEPS & CALIB_SKIP_DELAY_SWEEPS)
3401 					continue;
3402 
3403 				/* Calibrate WRITEs */
3404 				if (!rw_mgr_mem_calibrate_writes(rank_bgn,
3405 						write_group, write_test_bgn))
3406 					continue;
3407 
3408 				group_failed = 1;
3409 				if (!(gbl->phy_debug_mode_flags & PHY_DEBUG_SWEEP_ALL_GROUPS))
3410 					return 0;
3411 			}
3412 
3413 			/* Some group failed, we're done. */
3414 			if (group_failed)
3415 				goto grp_failed;
3416 
3417 			for (read_group = write_group * rwdqs_ratio,
3418 			     read_test_bgn = 0;
3419 			     read_group < (write_group + 1) * rwdqs_ratio;
3420 			     read_group++,
3421 			     read_test_bgn += rwcfg->mem_dq_per_read_dqs) {
3422 				if (STATIC_CALIB_STEPS & CALIB_SKIP_WRITES)
3423 					continue;
3424 
3425 				if (!rw_mgr_mem_calibrate_vfifo_end(read_group,
3426 								read_test_bgn))
3427 					continue;
3428 
3429 				if (!(gbl->phy_debug_mode_flags & PHY_DEBUG_SWEEP_ALL_GROUPS))
3430 					return 0;
3431 
3432 				/* The group failed, we're done. */
3433 				goto grp_failed;
3434 			}
3435 
3436 			/* No group failed, continue as usual. */
3437 			continue;
3438 
3439 grp_failed:		/* A group failed, increment the counter. */
3440 			failing_groups++;
3441 		}
3442 
3443 		/*
3444 		 * USER If there are any failing groups then report
3445 		 * the failure.
3446 		 */
3447 		if (failing_groups != 0)
3448 			return 0;
3449 
3450 		if (STATIC_CALIB_STEPS & CALIB_SKIP_LFIFO)
3451 			continue;
3452 
3453 		/* Calibrate the LFIFO */
3454 		if (!rw_mgr_mem_calibrate_lfifo())
3455 			return 0;
3456 	}
3457 
3458 	/*
3459 	 * Do not remove this line as it makes sure all of our decisions
3460 	 * have been applied.
3461 	 */
3462 	writel(0, &sdr_scc_mgr->update);
3463 	return 1;
3464 }
3465 
3466 /**
3467  * run_mem_calibrate() - Perform memory calibration
3468  *
3469  * This function triggers the entire memory calibration procedure.
3470  */
3471 static int run_mem_calibrate(void)
3472 {
3473 	int pass;
3474 
3475 	debug("%s:%d\n", __func__, __LINE__);
3476 
3477 	/* Reset pass/fail status shown on afi_cal_success/fail */
3478 	writel(PHY_MGR_CAL_RESET, &phy_mgr_cfg->cal_status);
3479 
3480 	/* Stop tracking manager. */
3481 	clrbits_le32(&sdr_ctrl->ctrl_cfg, 1 << 22);
3482 
3483 	phy_mgr_initialize();
3484 	rw_mgr_mem_initialize();
3485 
3486 	/* Perform the actual memory calibration. */
3487 	pass = mem_calibrate();
3488 
3489 	mem_precharge_and_activate();
3490 	writel(0, &phy_mgr_cmd->fifo_reset);
3491 
3492 	/* Handoff. */
3493 	rw_mgr_mem_handoff();
3494 	/*
3495 	 * In Hard PHY this is a 2-bit control:
3496 	 * 0: AFI Mux Select
3497 	 * 1: DDIO Mux Select
3498 	 */
3499 	writel(0x2, &phy_mgr_cfg->mux_sel);
3500 
3501 	/* Start tracking manager. */
3502 	setbits_le32(&sdr_ctrl->ctrl_cfg, 1 << 22);
3503 
3504 	return pass;
3505 }
3506 
3507 /**
3508  * debug_mem_calibrate() - Report result of memory calibration
3509  * @pass:	Value indicating whether calibration passed or failed
3510  *
3511  * This function reports the results of the memory calibration
3512  * and writes debug information into the register file.
3513  */
3514 static void debug_mem_calibrate(int pass)
3515 {
3516 	uint32_t debug_info;
3517 
3518 	if (pass) {
3519 		printf("%s: CALIBRATION PASSED\n", __FILE__);
3520 
3521 		gbl->fom_in /= 2;
3522 		gbl->fom_out /= 2;
3523 
3524 		if (gbl->fom_in > 0xff)
3525 			gbl->fom_in = 0xff;
3526 
3527 		if (gbl->fom_out > 0xff)
3528 			gbl->fom_out = 0xff;
3529 
3530 		/* Update the FOM in the register file */
3531 		debug_info = gbl->fom_in;
3532 		debug_info |= gbl->fom_out << 8;
3533 		writel(debug_info, &sdr_reg_file->fom);
3534 
3535 		writel(debug_info, &phy_mgr_cfg->cal_debug_info);
3536 		writel(PHY_MGR_CAL_SUCCESS, &phy_mgr_cfg->cal_status);
3537 	} else {
3538 		printf("%s: CALIBRATION FAILED\n", __FILE__);
3539 
3540 		debug_info = gbl->error_stage;
3541 		debug_info |= gbl->error_substage << 8;
3542 		debug_info |= gbl->error_group << 16;
3543 
3544 		writel(debug_info, &sdr_reg_file->failing_stage);
3545 		writel(debug_info, &phy_mgr_cfg->cal_debug_info);
3546 		writel(PHY_MGR_CAL_FAIL, &phy_mgr_cfg->cal_status);
3547 
3548 		/* Update the failing group/stage in the register file */
3549 		debug_info = gbl->error_stage;
3550 		debug_info |= gbl->error_substage << 8;
3551 		debug_info |= gbl->error_group << 16;
3552 		writel(debug_info, &sdr_reg_file->failing_stage);
3553 	}
3554 
3555 	printf("%s: Calibration complete\n", __FILE__);
3556 }
3557 
3558 /**
3559  * hc_initialize_rom_data() - Initialize ROM data
3560  *
3561  * Initialize ROM data.
3562  */
3563 static void hc_initialize_rom_data(void)
3564 {
3565 	unsigned int nelem = 0;
3566 	const u32 *rom_init;
3567 	u32 i, addr;
3568 
3569 	socfpga_get_seq_inst_init(&rom_init, &nelem);
3570 	addr = SDR_PHYGRP_RWMGRGRP_ADDRESS | RW_MGR_INST_ROM_WRITE_OFFSET;
3571 	for (i = 0; i < nelem; i++)
3572 		writel(rom_init[i], addr + (i << 2));
3573 
3574 	socfpga_get_seq_ac_init(&rom_init, &nelem);
3575 	addr = SDR_PHYGRP_RWMGRGRP_ADDRESS | RW_MGR_AC_ROM_WRITE_OFFSET;
3576 	for (i = 0; i < nelem; i++)
3577 		writel(rom_init[i], addr + (i << 2));
3578 }
3579 
3580 /**
3581  * initialize_reg_file() - Initialize SDR register file
3582  *
3583  * Initialize SDR register file.
3584  */
3585 static void initialize_reg_file(void)
3586 {
3587 	/* Initialize the register file with the correct data */
3588 	writel(REG_FILE_INIT_SEQ_SIGNATURE, &sdr_reg_file->signature);
3589 	writel(0, &sdr_reg_file->debug_data_addr);
3590 	writel(0, &sdr_reg_file->cur_stage);
3591 	writel(0, &sdr_reg_file->fom);
3592 	writel(0, &sdr_reg_file->failing_stage);
3593 	writel(0, &sdr_reg_file->debug1);
3594 	writel(0, &sdr_reg_file->debug2);
3595 }
3596 
3597 /**
3598  * initialize_hps_phy() - Initialize HPS PHY
3599  *
3600  * Initialize HPS PHY.
3601  */
3602 static void initialize_hps_phy(void)
3603 {
3604 	uint32_t reg;
3605 	/*
3606 	 * Tracking also gets configured here because it's in the
3607 	 * same register.
3608 	 */
3609 	uint32_t trk_sample_count = 7500;
3610 	uint32_t trk_long_idle_sample_count = (10 << 16) | 100;
3611 	/*
3612 	 * Format is number of outer loops in the 16 MSB, sample
3613 	 * count in 16 LSB.
3614 	 */
3615 
3616 	reg = 0;
3617 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_ACDELAYEN_SET(2);
3618 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_DQDELAYEN_SET(1);
3619 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_DQSDELAYEN_SET(1);
3620 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_DQSLOGICDELAYEN_SET(1);
3621 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_RESETDELAYEN_SET(0);
3622 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_LPDDRDIS_SET(1);
3623 	/*
3624 	 * This field selects the intrinsic latency to RDATA_EN/FULL path.
3625 	 * 00-bypass, 01- add 5 cycles, 10- add 10 cycles, 11- add 15 cycles.
3626 	 */
3627 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_ADDLATSEL_SET(0);
3628 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_SAMPLECOUNT_19_0_SET(
3629 		trk_sample_count);
3630 	writel(reg, &sdr_ctrl->phy_ctrl0);
3631 
3632 	reg = 0;
3633 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_1_SAMPLECOUNT_31_20_SET(
3634 		trk_sample_count >>
3635 		SDR_CTRLGRP_PHYCTRL_PHYCTRL_0_SAMPLECOUNT_19_0_WIDTH);
3636 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_1_LONGIDLESAMPLECOUNT_19_0_SET(
3637 		trk_long_idle_sample_count);
3638 	writel(reg, &sdr_ctrl->phy_ctrl1);
3639 
3640 	reg = 0;
3641 	reg |= SDR_CTRLGRP_PHYCTRL_PHYCTRL_2_LONGIDLESAMPLECOUNT_31_20_SET(
3642 		trk_long_idle_sample_count >>
3643 		SDR_CTRLGRP_PHYCTRL_PHYCTRL_1_LONGIDLESAMPLECOUNT_19_0_WIDTH);
3644 	writel(reg, &sdr_ctrl->phy_ctrl2);
3645 }
3646 
3647 /**
3648  * initialize_tracking() - Initialize tracking
3649  *
3650  * Initialize the register file with usable initial data.
3651  */
3652 static void initialize_tracking(void)
3653 {
3654 	/*
3655 	 * Initialize the register file with the correct data.
3656 	 * Compute usable version of value in case we skip full
3657 	 * computation later.
3658 	 */
3659 	writel(DIV_ROUND_UP(iocfg->delay_per_opa_tap, iocfg->delay_per_dchain_tap) - 1,
3660 	       &sdr_reg_file->dtaps_per_ptap);
3661 
3662 	/* trk_sample_count */
3663 	writel(7500, &sdr_reg_file->trk_sample_count);
3664 
3665 	/* longidle outer loop [15:0] */
3666 	writel((10 << 16) | (100 << 0), &sdr_reg_file->trk_longidle);
3667 
3668 	/*
3669 	 * longidle sample count [31:24]
3670 	 * trfc, worst case of 933Mhz 4Gb [23:16]
3671 	 * trcd, worst case [15:8]
3672 	 * vfifo wait [7:0]
3673 	 */
3674 	writel((243 << 24) | (14 << 16) | (10 << 8) | (4 << 0),
3675 	       &sdr_reg_file->delays);
3676 
3677 	/* mux delay */
3678 	writel((rwcfg->idle << 24) | (rwcfg->activate_1 << 16) |
3679 	       (rwcfg->sgle_read << 8) | (rwcfg->precharge_all << 0),
3680 	       &sdr_reg_file->trk_rw_mgr_addr);
3681 
3682 	writel(rwcfg->mem_if_read_dqs_width,
3683 	       &sdr_reg_file->trk_read_dqs_width);
3684 
3685 	/* trefi [7:0] */
3686 	writel((rwcfg->refresh_all << 24) | (1000 << 0),
3687 	       &sdr_reg_file->trk_rfsh);
3688 }
3689 
3690 int sdram_calibration_full(void)
3691 {
3692 	struct param_type my_param;
3693 	struct gbl_type my_gbl;
3694 	uint32_t pass;
3695 
3696 	memset(&my_param, 0, sizeof(my_param));
3697 	memset(&my_gbl, 0, sizeof(my_gbl));
3698 
3699 	param = &my_param;
3700 	gbl = &my_gbl;
3701 
3702 	rwcfg = socfpga_get_sdram_rwmgr_config();
3703 	iocfg = socfpga_get_sdram_io_config();
3704 	misccfg = socfpga_get_sdram_misc_config();
3705 
3706 	/* Set the calibration enabled by default */
3707 	gbl->phy_debug_mode_flags |= PHY_DEBUG_ENABLE_CAL_RPT;
3708 	/*
3709 	 * Only sweep all groups (regardless of fail state) by default
3710 	 * Set enabled read test by default.
3711 	 */
3712 #if DISABLE_GUARANTEED_READ
3713 	gbl->phy_debug_mode_flags |= PHY_DEBUG_DISABLE_GUARANTEED_READ;
3714 #endif
3715 	/* Initialize the register file */
3716 	initialize_reg_file();
3717 
3718 	/* Initialize any PHY CSR */
3719 	initialize_hps_phy();
3720 
3721 	scc_mgr_initialize();
3722 
3723 	initialize_tracking();
3724 
3725 	printf("%s: Preparing to start memory calibration\n", __FILE__);
3726 
3727 	debug("%s:%d\n", __func__, __LINE__);
3728 	debug_cond(DLEVEL == 1,
3729 		   "DDR3 FULL_RATE ranks=%u cs/dimm=%u dq/dqs=%u,%u vg/dqs=%u,%u ",
3730 		   rwcfg->mem_number_of_ranks, rwcfg->mem_number_of_cs_per_dimm,
3731 		   rwcfg->mem_dq_per_read_dqs, rwcfg->mem_dq_per_write_dqs,
3732 		   rwcfg->mem_virtual_groups_per_read_dqs,
3733 		   rwcfg->mem_virtual_groups_per_write_dqs);
3734 	debug_cond(DLEVEL == 1,
3735 		   "dqs=%u,%u dq=%u dm=%u ptap_delay=%u dtap_delay=%u ",
3736 		   rwcfg->mem_if_read_dqs_width, rwcfg->mem_if_write_dqs_width,
3737 		   rwcfg->mem_data_width, rwcfg->mem_data_mask_width,
3738 		   iocfg->delay_per_opa_tap, iocfg->delay_per_dchain_tap);
3739 	debug_cond(DLEVEL == 1, "dtap_dqsen_delay=%u, dll=%u",
3740 		   iocfg->delay_per_dqs_en_dchain_tap, iocfg->dll_chain_length);
3741 	debug_cond(DLEVEL == 1, "max values: en_p=%u dqdqs_p=%u en_d=%u dqs_in_d=%u ",
3742 		   iocfg->dqs_en_phase_max, iocfg->dqdqs_out_phase_max,
3743 		   iocfg->dqs_en_delay_max, iocfg->dqs_in_delay_max);
3744 	debug_cond(DLEVEL == 1, "io_in_d=%u io_out1_d=%u io_out2_d=%u ",
3745 		   iocfg->io_in_delay_max, iocfg->io_out1_delay_max,
3746 		   iocfg->io_out2_delay_max);
3747 	debug_cond(DLEVEL == 1, "dqs_in_reserve=%u dqs_out_reserve=%u\n",
3748 		   iocfg->dqs_in_reserve, iocfg->dqs_out_reserve);
3749 
3750 	hc_initialize_rom_data();
3751 
3752 	/* update info for sims */
3753 	reg_file_set_stage(CAL_STAGE_NIL);
3754 	reg_file_set_group(0);
3755 
3756 	/*
3757 	 * Load global needed for those actions that require
3758 	 * some dynamic calibration support.
3759 	 */
3760 	dyn_calib_steps = STATIC_CALIB_STEPS;
3761 	/*
3762 	 * Load global to allow dynamic selection of delay loop settings
3763 	 * based on calibration mode.
3764 	 */
3765 	if (!(dyn_calib_steps & CALIB_SKIP_DELAY_LOOPS))
3766 		skip_delay_mask = 0xff;
3767 	else
3768 		skip_delay_mask = 0x0;
3769 
3770 	pass = run_mem_calibrate();
3771 	debug_mem_calibrate(pass);
3772 	return pass;
3773 }
3774