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