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