Sunday, 3 April 2016

Code cleanup and refactoring in MDK-OS Clock setup

Clocks form an important part in any embedded system and configuration of this clock tree is very error prone. In the present code clean up I have parametrized the existing configurations which were hard coded. This is very error prone as any change in the base clock speed would cause a mismatch with the configuration.

The first step I took in refactoring my code was to have helper functions to get FCLK, HCLK and PCLK. In the same vein I created a conditional compilation set up which compiles based on the board i.e. it being a MINI2440 or a MINI2410 etc. From the clock point of view the crystal used in these boards varies. The MINI2440 uses a clock source derived from a crystal based on OM3 and OM2 pins. The crystal as per the schematic is a 12Mhz crystal.

With this as the base and using the helper functions the whole clock tree settings i.e the pre-scaler can be automated for different peripherals such as UART, SD MMC using formulae rather than hard coding values.

First we will try to understand the different clocks signals generated by the control logic. There are 3 clock signals generated FCLK for the CPU, HCLK for the AHB bus peripherals, and PCLK for the APB bus peripherals.

The S3C2440 has  2 PLL's one for FCLK, HCLK and PCLK and the other dedicated for USB block (48 MHz). The control logic can make slow clocks without the PLL's.

What is a PLL and what does it do? PLL or a Phase Locked Loop is a control system which generates an output signal whose phase is related to the phase of the input signal.  Generally we use a PLL to generate a multiple of the input frequency. So the input to the PLL is a oscillator and output is a multiple of the input frequency. So in our case we have a 12MHz crystal oscillator which is given to the PLL's to generate multiples and keeping the phase locked with the input and output frequencies.
PLL's take time to stabilize. Hence there should be a way for the chip to work based on the oscillator frequency or an external signal. Once the PLL stabilizes and is able to generate a clean signal the chip can switch to the PLL frequency.

The following is the clock architecture of the S3C2440.


The main clock comes from the external crystal (XTlpll) or an external clock (EXTCLK). The clock generator includes an oscillator (Oscillation Amplifier), which is connected to an external crystal, and also has two PLL's (Phase locked loop) which generate the high frequency clock required in the S3C2440A.


 The OM[3:2] status is latched internally by referring the OM3 and OM2 pins at the rising edge of nRESET as shown below

According to the data sheet the clock selection during boot-up is Crystal for the main clock source and USB.

The MPLL  starts just after a reset but the MPLL output is not used as the system clock until the software writes valid settings to the MPLLCON register. Before these settings, the clock from the external crystal or EXTCLK source will be used as the system clock directly. Even if the user does not want to change the default value of the MPLLCON register, the user should write the same value into the MPLLCON register.

After the power on reset the crystal oscillator begins oscillation within several milliseconds. When nRESET is released after the OSC (XTIpll) clock the PLL starts to operate according the default PLL configuration. However the PLL is commonly known to be unstable after power-on reset so Fin is fed directly to the FCLK instead of the Mpll (PLL output) before the software newly configures PLLCON.

The PLL restarts the lockup sequence toward the new frequency only after the software configures the PLL with a new frequency. FCLK can be configured as PLL output (Mpll) immediately after lock time.

The wave form diagram below gives a clearer picture


For USB clock control and USB device interface needs 48MHz clock hence a dedicated USB PLL (UPLL) generates the clock.

Now we come to coding the clock setup. The clock setup has to be parameterized.

We come to the init_clock(..) function. Here we set the clock lock time to maximum. Next we do a set_clock_divn(..). Here we set the dividers. We divide the FCLK by 1, HDIVN by 4 and PDIVN by 8. Note that MPLL is fed into the CLKCNTL logic which generates the FCLK.



1
2
3
4
 set_clock_divn(CLK_BASE_ADDR,
     DIVN_UPLL_BY_1,
     HDIVN_FCLK_BY_4,
     PDIVN_HCLK_BY_2);


So the final clock setup would be:

 FCLK = 405 MHz.
 HCLK = 405/4 = 101MHz
 PCLK = 405/8 = 50 MHz

 We need to setup the CPU to asynchronous mode. We can see the P 2-11 of ARM920T (Chapter 5). Also S3C2440 does not support synchronous mode.

The code is as follows:


1
2
3
4
5
6
7
8
__asm__ __volatile__(
  "mrc p15,0,r1,c1,c0,0\n\t"
  "orr r1,r1,#0xC0000000\n\t"
  "mcr p15,0,r1,c1,c0,0\n\t"
  : /* No output */
  : /* No input */
  : "r1" /* r1 clobbered */
  );

Next we have to set the 2 PLL's. MPLL and UPLL.

First we set the UPLL to generate 48 MHz as follows:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 set_clk_upll(CLK_BASE_ADDR,0x38,0x2,0x2); //48 MHz.
    
 __asm__ __volatile__(
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
  );

Note the mov r0,r0. This is used generate at least 7 NOPs.

Next we set the MPLL to 405 MHz  as follows:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 set_clk_mpll(CLK_BASE_ADDR,0x7f,0x2,0x1); //405 MHz

 __asm__ __volatile__(
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
   "mov r0,r0\n\t"
  );

Finally we clear the slow clock register bits as follows.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#define clear_slow_clock(BA) do { \
 clear_reg_bits(CLKSLOW_REG(BA),UCLK_ON); \
 clear_reg_bits(CLKSLOW_REG(BA),MPLL_OFF); \
 __asm__ __volatile__ ( \
  "mov r0,r0 \n\t"  \
  "mov r0,r0 \n\t"  \
  "mov r0,r0 \n\t"  \
  "mov r0,r0 \n\t"  \
  "mov r0,r0 \n\t"  \
  "mov r0,r0 \n\t"  \
 ); \
 clear_reg_bits(CLKSLOW_REG(BA),SLOW_BIT); \
 } while(0)

We clear the UCLK bit to turn on UPL. Next we turn on the MPLL and allow it settle which takes 300us. Hence we have NOPs for the delay. After this we turn OFF the slow clock to set the MPLL to the FCLK.


To get the current clocks I have written utility functions so that I can derive the different clocks just by reading the registers itself.

First I have helper functions to get the dividers as follows:


1
2
3
4
5
6
7
8
#define get_clk_pll_mdiv(PLL_REG) \
 (((readreg32(PLL_REG)) & MDIV_MASK) >> MDIV_SHIFT)

#define get_clk_pll_pdiv(PLL_REG) \
 (((readreg32(PLL_REG)) & PDIV_MASK) >> PDIV_SHIFT)

#define get_clk_pll_sdiv(PLL_REG) \
 (((readreg32(PLL_REG)) & SDIV_MASK) >> SDIV_SHIFT)

Next I get the 2 PLL clock i.e. UPLL and MPLL based on the following helper functions:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
uint32_t get_mpll_clk(uint32_t BA)
{
 uint32_t m,p,s;
 
 m = get_clk_pll_mdiv(MPLLCON_REG(BA)) + 8;
 p = get_clk_pll_pdiv(MPLLCON_REG(BA)) + 2;
 s = get_clk_pll_sdiv(MPLLCON_REG(BA));

 return ((m * S3C_CLOCK_REFERENCE) * 2)/(p * (1<<s));
}


uint32_t get_upll_clk(uint32_t BA)
{
 
 uint32_t m,p,s;
 
 m = get_clk_pll_mdiv(UPLLCON_REG(BA)) + 8;
 p = get_clk_pll_pdiv(UPLLCON_REG(BA)) + 2;
 s = get_clk_pll_sdiv(UPLLCON_REG(BA));

 return (m * S3C_CLOCK_REFERENCE)/(p * (1<<s));
}

To explain the above code I have to bring out the formulae. According the datasheet:

MPLL Control Register

Mpll = (2 * m * Fin) / (p * 2 S)
m = (MDIV + 8), p = (PDIV + 2), s = SDIV

UPLL Control Register

Upll = (m * Fin) / (p * 2 S)
m = (MDIV + 8), p = (PDIV + 2), s = SDIV



Hence we get the m, p and s.

Next we have the formula:

PLL Value Selection Guide (MPLLCON)
  1.  Fout = 2 * m * Fin / (p*(2^s) ), Fvco = 2 * m * Fin / p where: m=MDIV+8, p=PDIV+2, s=SDIV
  2.  600MHz ≤ FVCO ≤ 1.2GHz
  3.  200MHz ≤ FCLK OUT ≤ 600MHz
In the above code we return the Fout formula.

So to finally get the FCLK, HCLK,PCLK and the UCLK we have to check the dividers. We do divide the FCLK so we use Fout as is. Next for HCLK,PCLK and UCLK we have the following code:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
uint32_t get_hclk(uint32_t BA)
{
 uint32_t fclk = get_fclk(BA);

 switch(get_clock_hdivn(BA)) {
  case HDIVN_FCLK_BY_1:
   return fclk;
  case HDIVN_FCLK_BY_2:
   return (fclk >> 1);
  case HDIVN_FCLK_BY_4:
   //TODO: CAMDIVN conditon check pending.
   return (fclk >> 2);
  case HDIVN_FCLK_BY_3:
   //TODO: CAMDIVN conditon check pending.
   return (fclk / 3);
 }

 return fclk;
}

uint32_t get_pclk(uint32_t BA)
{
 uint32_t hclk = get_hclk(BA);

 switch(get_clock_pdivn(BA)) {
  case PDIVN_HCLK_BY_1:
   return hclk;
  case PDIVN_HCLK_BY_2:
   return hclk >> 1;
 }

 return hclk;
}

uint32_t get_uclk(uint32_t BA)
{
 uint32_t uclk = get_upll_clk(BA);

 switch(get_clock_upll_divn(BA)) {
  case DIVN_UPLL_BY_1:
   return uclk;
  case DIVN_UPLL_BY_2:
   return uclk >> 2;
 }

 return uclk;
}


Note that the FCLK forms the base for the HCLK i.e. we divide the FCLK to get the HCLK. Next for the PCLK, HCLK forms the base i.e. we divide the HCLK to get the PCLK.

For the UCLK we have the UPLL and hence we check the UDIVN and divide to get the final clock.

So there you have it. The clock setup for the S3C2440.

Time is an illusion
--Albert Einstein

Procuring and sourcing electronic components in India

The one thing that an embedded engineer needs is a lot of electronic components and boards and a decent low cost lab at home. I will write about my sources in procuring and sourcing components in India so that it helps others looking for answers to this.

The first thing that comes to mind for electronics enthusiasts in Bangalore is SP Road. Here you can get a lot of electronic components. I generally go to Vishal electronics but you should explore different shops and find what is needed and select what best fits you. Also do not forget to bargain. Before going there prepare a list and shop fast. The parking situation is horrible and your vehicle can get towed for no reason.

Some of the things you can buy in cheap for a small home lab setup are:
  1. Discrete components. (Resistors, capacitors, transistors, LED's etc). You would generally get through hole types but sometimes SMD components as well. There might be defective parts hence beware. Also since the handling of different components is really questionable be prepared for ESD issues in components.
  2. Soldering station and different solder tips.
  3. Magnifying glass. (Really need this to inspect your soldering and also seeing tiny parts in your PCB's).
  4. Cleaning alcohol solutions
  5. Cables, solder, solder paste  and solder braids (for de-soldering).
  6. Tweezers for holding the components in place while soldering so that you don't burn your fingers.
  7. Bread boards.
  8. Jumper cables. 
  9. Various interface cables such as RS232, USB to serial cables, Straight and cross cables etc. You get the choice of crimping done there.
I generally buy the above stuff in SP road. I generally tend to stay away from buying micro-controller’s or development boards from them because of poor handling but I have started looking at cheaper micro-controllers there.

Apart from this we have some pretty good online stores in India. Some of them are mentioned below:

  1. Tenet Technetronics ( http://tenettech.com  ) -- Slow delivery. I got my two MINI2440's from here. Apart from that I got myself a Nooelec SDR.
  2. Protocentral ( https://www.protocentral.com ) --  Fast delivery. Quite costly for simple items. You can find a lot of sparkfun and adafruit designs here.
  3. Kits 'n' spares ( http://kitsnspares.com ) -- You get element14 parts as element14 requires you to have a TIN number. Delivery is slow and also they are not organized. You have to follow up them with your orders or it will take a really long time for them to deliver. I got my MSP430 boards from here.
  4. Crazypi ( https://www.crazypi.com/ ) -- Misleading name as you would think they deal with only Raspberry Pi solutions. They deal with ARM SBC's. I got my  TI ARM Sitara based beaglebone from here. You can either go directly to their store or you can order from their website. Good service.
  5. Innovate solutions ( https://www.innovatesolutions.net/ ) -- Deals with ARM SBC's and microcontrollers, debuggers etc.  I got my i.MX6 based wandboard from here. You can also walk into their store to buy your items.
  6. Rhydo labz ( http://www.rhydolabz.com/ ) -- Personally I have not bought anything from here but heard they are good. You have a good selection of components and boards.
  7. Amazon -- Good passive kits such as resistors, capacitors and transistors
  8. Quad Store ( https://quadstore.in/ )  -- Very good collection for different sensors
For some of the boards I bought it directly from the vendor store or their partners. Some of them are:

  1. TI eStore ( https://store.ti.com/ ) -- Expensive and they only accept credit cards. Good board packaging so no worry about ESD's. Surprisingly fast delivery. I bought my MSP430 launchpads as well as MSP430 through hole package sample chips from them.
  2. Coreel Technologies ( http://www.coreel.com/ ) -- I bought a FPGA Digilent Basys 2 board from them. Expensive but they offer guarantees and warranties. Good packaging.

It is a good idea to invest some money on an oscilloscope. I have a Rigol  DS1102E two channel 100MHz oscilloscope. It is a really nice scope for a low price compared to a Tektronix or an Agilent. It costed me Rs 31500. You can buy it when they offer discounts. I bought it from Salicon Tech ( http://www.salicontech.com ). The prices are slightly expensive but the service is good. They provide after sales service provided you bear the cost. (Shipping + repair).

Apart from this you can always order free samples of different chips from different manufacturers and vendors to try it out in your designs. I got some free samples from FriendlyARM which I have detailed in my previous posts.

Apart from these have good relations with the vendor FAE's and always ask/bug them for development boards/parts whenever you meet them. They generally have some boards/chips lying around or they can offer you some refurbished boards or they will have connections which will allow you to get some boards/chips/parts at massive discounts.

Hope I have covered most of the things. I will edit this post from time to time if I find good vendors.

“Artists work best alone. Work alone.”
― Steve Wozniak,
iWoz

Friday, 18 March 2016

Basic u-boot setup for porting

I have been doing some work on u-boot porting and I felt that I should write a small step by step guide for my reference.

  1. Pull the u-boot source from git repo.
  2. Create a separate branch. In this way you are creating
       isolating your changes to a separate branch. Once testing
       is done and is stable you can merge to the main branch.
       eg: git branch <yourbranchname> 
  3. Checkout to your branch.   eg: git checkout <yourbranchname> 
  4. Now we are ready to port u-boot to the new board. 
  5. Create a folder called <yourboardname> in board/vendor/
       eg: board/vendor/<yourboardname>
  6. Populate this folder with Kconfig,Makefile,<yourboardname>.c, any lds (linker script files) at a minimum.
    Modify Kconfig and Makefile accordingly. Any supporting files can be put in the above folder. 
  7. Create a configuration file in include/configs/<yourboardname>.h
  8. Create a defconfig file in configs/<yourboardname>_defconfig
  9. Edit arch/<cpu_architecture>/cpu/<cpu_architecture_variant>/<cpu_vendor>/Kconfig
        eg: arch/arm/cpu/armv7/mx6/Kconfig 
  10. Create a section TARGET_<yourboardname>
                        <...>
                        <...>
                        <...>
  11.  At the end of the file add the source path.
     eg: source "board/<vendor>/<yourboardname>/Kconfig"
  12.  Run
        CROSS_COMPILE="<yourcompilertoolchain>" make distclean
        CROSS_COMPILE="<yourcompilertoolchain>" make <yourboardname>_defconfig
        CROSS_COMPILE="<yourcompilertoolchain>" make
  13.  To flash the board with your new u-boot do:
        sudo dd if=u-boot.imx of=/dev/sdb bs=512 seek=2 conv=fsync

If you have a board similar to already existing boards use the configurations present
in the already existing board to jump start your changes.

No man should escape our universities without knowing how little he knows.
-J. Robert Oppenheimer
 





Saturday, 20 February 2016

On job opportunities in bare metal programming.

A shameless plug,  if anybody needs to have bare metal firmware developed and need help in implementing it please leave a message. It would be great if you are hiring as I am open to good career opportunities.

USB Development on the S3C2440 update

Long time since my last post.  I had initially started off with the ethernet driver development but kept it pending due the lack of understanding of the timing diagrams. In its place I have started off with USB development. I will have a detailed write up once I have something going.

Thursday, 28 January 2016

FriendlyARM Nano Pi2 review

I received two NanoPi2 samples from FriendlyARM somewhere around the first week of January. It took more than month to reach India from China using China Post. 

I was very excited about this as you would already know that I am developing a baremetal OS for the older mini2440. I had been informed that the mini2440 is out of production and in its place the newer and much smaller NanoPI with the S3C2451 chip is made available.

Just a few details about the NanoPi, it is a ARM9 S3C2451 chip running at 400Mhz with 64MB of DDR2. It has the usual interfaces as present in the S3C2440 based Mini2440 board.

Now coming to the NanoPi2 what is really impressive is the size of this thing. It has a size of 75mmx40mm. It is lesser than the size of a credit card approaching the size of a USB dongle.  FriendlyARM has done a real good job in making a board with such a small form factor.

The NanoPi2 comes packed with Samsung S5P 4418 Quad Core Cortex-A9 at 1.4G Hz with 1GB 32bit DDR3 RAM. As you would know for my baremetal programming I am mainly interested in the processor and RAM. Once I get this beast up, rest of the things follow much faster. There are two micro SD Slots, a USB 2.0 Host Type A, a micro USB for data input and power. It has 40 pin GPIO good enough for plenty of debugging.

It has pins for camera and LCD connections and HDMI output.

From the connectivity side it has Wifi and Bluetooth support with BLE4.0.

There is support for Linux (Debian Jessie) and Android (4.4.2) Kitkat.

 Now for the unboxing and setup. The NanoPi2 comes in a neat card board case. It looks like a wallet and is beautiful.



Side view of the beautiful card board case



Size comparison of the NanoPi2 with my meal pass card. It is really impressive.



The NanoPi2 connected to the PSU and RS232 board which is provided separately.





Finally I got this  cute NanoPi2 case to put into. I am not sure whether it is 3D printed but it sure looks like it. It looks like a cute soap box.




Debian Jessie running out of the box with the HDMI output connected to my monitor. You can also find my dear MINI2440 board photo bombing at the right side :)



This is a really neat evaluation board for Robotics, IoT with its Bluetooth and Wifi connectivity. Considering how small it is I think it also goes well with controlling of drones.
This is also a really good board for the maker community.

I am really excited in developing for this board especially to try to see if I can get my baremetal OS running on it.

Special thanks to Friendly ARM for gifting two samples of this board and kudos to them for making boards with such impressive form factor and functionality.

Simplicity is prerequisite for reliability. -- Edsger W. Dijkstra

Wednesday, 27 January 2016

MINI2440 memory address banks and SDRAM setup.

Initially the loader can be booted up without setting the RAM. This is achieved by the stepping stone controller. This controller fetches first 4KB of data from the NAND flash and places it in the 4KB SRAM called the stepping stone buffer.


This SRAM is good enough for the loader to load the MDK OS. To do anything serious we need to setup the SDRAM.

My setup:

In my MINI2440 board I have two Samsung K4S561632N SDRAM chips each of size 32MB totalling 64MB of SDRAM.


To proceed further we need to understand the datasheet thoroughly.

From the datasheet we have:
    The K4S560432N / K4S560832N / K4S561632N is 268,435,456 bits synchronous high data rate Dynamic RAM organized as 4 x 16,777,216 words by 4 bits / 4 x 8,388,608 words by 8bits / 4 x 4,194,304 words by 16bits.
The SRAM type table is as follows:




Our memory being the K4S561632N its organization is 4 x 4,194,304 words by 16bits (i.e. 16M x 16). The x16 forms the data bus width i.e. 16 bits or 2 bytes. The "words" in the above sentence means this data bus width i.e. 16 bits. Hence the SDRAM outputs a "word".

Also here 268,435,456 bits is 32MB or 256Mb.

Notice that all the memories have "4 x " prefix. This is because all these memories  have 4 banks and therefore are 4 bank operation chips.

The organization in the data sheet is as follows for the 3 different memories:



In this case our memory organization is the 16Mx16 with Row Address from A0~A12 and Column Address from A0-A8.

Hence we can have 2^13 addressable rows and 2^9 addressable columns to make it 4194304 addressable words in each bank. Hence 4 banks x 4194304 addressable words become a total of 16777216 words. Since each word is 16 bits or 2 bytes the chip capacity is 32MB (=16777216 x 2 bytes (16 bits) = 33554432 or 32MB).

Similarly we can figure out the numbers for the other 2 memories.

For the K4S560832N:
4 x 8,388,608 words = 33554432 words.
Since it is 8 bits per word or 1 byte per word it is 33554432 x 1 = 33554432 or 32MB.

For the K4S560432N:
4 x 16,777,216 = 67108864 words.
Since it is 4 bits per word or 1/2 a byte per word it is 67108864 x 1/2 = 33554432 or 32MB.


Now we come to how these memory chips are wired to our processor. A diagram of how the chips are wired to the processor is below (ASCII art courtesy of Juergen Borleis of Pengutronix mailing list for helping me understand the bank map configuration):

----------+      /CS to bank#2
          |----------------------------------------------------------
          |                                            |            |
S3C2440   |      /CS to bank#1                         |            |
          |------------------------------              |            |
          |                  |          |              |            |
          |             +--------+  +--------+     +--------+   +--------+
          |             | SDRAM1 |  | SDRAM2 |     | SDRAM3 |   | SDRAM4 |
          |             |        |  |        |     |        |   |        |
          |             +--------+  +--------+     +--------+   +--------+
          |            0..15 |          |16..31   0..15|            |16..31
          |                  |          |              |            |
          |----------------------------------------------------------
          |  32 bit databus
          |
----------+


If we go back to schematic we can find that nGCS6 with net name LLnSCS0 is connected to nSCS (SDRAM Chip Select) input of the two 32 MB chips.




Coming back to the data sheet we see that nGCS6 starts at memory address 0x30000000. Hence our SDRAM memory address starts from 0x30000000. The snapshot of the memory map is below:

According to the data sheet the nGCS6 forms Bank 6. Hence the two SDRAM chips are connected to Bank6 with both 16 bit bus width forming connected to the 32 bit data bus of the processor. You can verify this in the schematic snapshot below:



 You can see that the LDATA0 to LDATA15 connections from chip1 and LDATA16 to LDATA31 from chip2 forming the 32 bit data bus width.

When an address say 'A' is sent on the address lines for a read from the address then the chip U6 will respond with the data set in address 'A' through LDATA0 - LDATA15. Since the same address lines are fed to chip U7 it too responds with the data set in address 'A' through LDATA16 - LDATA31. When a write is done to address 'A', the first 16 bit data is set in the address 'A' of chip U6 and the send 16 bit data is set in address 'A' of chip U7.

Notice that the address pin connections start at ADDR2. For a 32 bit data bus the address is at 4 byte boundaries.


Notice that LADDR24 and LADDR25 lines are set as inputs to BA0 and BA1 respectively. BA0 and BA1 forms bank select pins for the chip.

Now why is LADDR24 and LADDR25 pins selected? 
  1. There are 4 banks per chip. Hence the 2 bit combination will allow to select the 4 banks.
  2. If the bits below LADDR24 are set to 1 it becomes 0xFFFFFF which is 16777215(starting from 0) which is the size of the 4 banks. (4 x4M words). Since the address starts at LADDR2 shift the LADDR24 and LADDR25 by 2 bits to the right. Now we get 0x3FFFFF which is 4194303 (starting from 0) which is the size of the single bank. A 4194304 address switches the bank to 1.  Hence as far as I see this is the explanation for the bank switching using the addresses themselves i.e. when the bits of the addresses corresponding to banks change there is a bank switch.

Register setup:

We finally come to source code for the SDRAM setup. 
First we need to configure Bus Width and Wait Control register (BWSCON)
The code is as follows:

1
2
3
4
5
6
7
8
void config_bwscon()
{

 /* Configure BWSCON */
 writereg32(BWSCON_REG(MEM_BA),
   DW7_RESERVED|DW6_32b|DW5_RESERVED|DW4_RESERVED|
   DW3_RESERVED|DW2_RESERVED|DW1_RESERVED);
}

Here the DW6 parameter is set to DW6_32b i.e. bus width as 32 bit.

My SDRAM init is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void sdram_init()
{

 config_bwscon();

 /* Configure BANKCON6/BANKCON7 */
 writereg32(BANKCON6_REG(MEM_BA),MT_SYNC_DRAM|SCAN_9BIT);

 /* 
  * Set BANKCON7 to ROM/SRAM i.e 00 and not SYNC_DRAM.
  * Rest of the values should not be used as they are reserved
  * Default value is SYNC_DRAM which should not be used.
  */
 writereg32(BANKCON7_REG(MEM_BA),MT_ROM_SRAM);

 /* Configure SDRAM Refresh settings */
 writereg32(REFRESHCTL_REG(MEM_BA),REFEN|Tsrc_5|1269);

 /* Configure Banksize setting */
 writereg32(BANKSIZE_REG(MEM_BA),BURST_EN|SCKE_EN|SCLK_EN|BK76MAP_64MB);

 /* Configure mode set register for BANK6 */
 writereg32(MRSRB6_REG(MEM_BA),CAS_LATENCY_2CLK);

 return;
}

I set the BANKCON6 register to Sync DRAM as it is SDRAM (Synchronous DRAM). For the memory type of SDRAM I set SCAN parameter to SCAN_9BIT as it is A0-A8 or 9 bit.

Bank7  has to be disabled. Set the BANKCON7 register to MT_ROM_SRAM as it is set default to MT_SYNC_DRAM which should be removed.

There is Trcd or RAS to CAS delay to set. In the datasheet the RAS to CAS latency or Trcd(min) is 20ns. In our processor we have setup the HCLK to be 101 Mhz or 9.99ns ~ 10ns. Hence we have to setup or Trcd to have to 2 clock delay which is 00.

Refresh control register (REFRESH):
We set REFEN which is self auto refresh.
We set TREFMD to 0 CBR/Auto refresh mode.
We set the SDRAM RAS pre-charge time to 2 clocks i.e. value 00 as the data sheet gives a tRP(min) as 20ns or 2 clock cycles.
We set the SDRAM semi row cycle time Tsrc to Tsrc_5. The calculation is as follows:

Trc = Tsrc + Trp
or
Tsrc = Trc - Trp

From the data sheet we have Trc as 65ns Trp as 20 ns. Hence we get Tsrc as 45ns. Hence we set Tsrc_5 which is 5 clocks or 50ns.

I set the refresh counter to 1269 as given in the data sheet example.

Banksize register settings (BANKSIZE):
Here I enable BURST_EN(burst enable), SCKE_EN (SDRAM power down mode enable), SCLK_EN (SCLK being enabled during SDRAM access cycle to reduce power consumption) and BANK76MAP set to 001 or 64MB as the size of the memory is 32MiB + 32MiB = 64MiB.

SDRAM Mode register set register (MRSR):
We simply set the CL parameter or the CAS Latency to 2 clocks. According to the data sheet the CAS latency is 2.

 A note on the memory controller bank select:

The S3C2440 has 8 memory banks. The General Chip select or nGCS should be connected to the different chip selects of the various peripherals connected which use the address space.
The banks are activated when the address of a memory is within the address region of the bank. This takes the burden out of doing a chip select manually whenever you want to access the memory region. Hence you can multiplex the address lines to different chips in different banks. When an address is generated the chip in the memory region is automatically selected using the bank chip select signal. I will verify this and provide an oscilloscope trace.

For reference from the data sheet:





Conclusion:
We do all the SDRAM setup in the loader itself as the MDK OS is loaded onto the SDRAM.

References: http://thread.gmane.org/gmane.comp.embedded.ptxdist.oselas.community/1994/focus=2010

Schematics from FriendlyARM.
Data sheet snapshots from Samsung S3C2440 data sheet.
Memory organization snap shots from Samsung K4S561632N data sheet.

It is better to do the right problem the wrong way than the wrong problem the right way.  --Richard Hamming