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