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