summaryrefslogtreecommitdiff
path: root/cleopatre/u-boot-1.1.6/board/sdk300/flash.c
blob: 571d8246e6663b9392e5a809814d4e0fea5eef3d (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
/*
 * board/sdk300/flash_spi.c
 *
 * Copyright (C) 2009 SPiDCOM Technologies
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 *
 * Author(s):
 * Drasko DRASKOVIC, drasko.draskovic@spidcom.com
 */

#include <common.h>
#include <malloc.h>
#include <asm/arch/nvram.h>

//#define DEBUG_FLASH_SPI

DECLARE_GLOBAL_DATA_PTR;

extern void flush_dcache(void);

/* Flash Organization Structure */
typedef struct OrgDef
{
	unsigned int sector_number;
	unsigned int sector_size;
} OrgDef;

flash_info_t flash_info[CFG_MAX_FLASH_BANKS]; /* info for FLASH chips */

#define IS_ATMEL_FLASH(id)      (((id) & 0x00FF0000) == 0x1F0000)

/* OPCODES (all one byte long for Spansion S25FL064A SPI Flash */

/* write */
#define READ      (unsigned char)(0x03)   /* Read Data Bytes */
#define FAST_READ (unsigned char)(0x0B)   /* Read Data Bytes at Higher Speed */
#define RDID      (unsigned char)(0x9F)   /* Read Identification */

/* write */
#define WREN      (unsigned char)(0x06)   /* Write Enable */
#define WRDI      (unsigned char)(0x04)   /* Write Disable */

/* erase */
#define SE        (unsigned char)(0xD8)   /* Sector Erase */
#define BE        (unsigned char)(0xC7)   /* Bulk (Chip) Erase */

/* program */
#define PP        (unsigned char)(0x02)   /* Page Program */

/* Status Register */
#define RDSR      (unsigned char)(0x05)   /* Read from Status Register */
#define WRSR      (unsigned char)(0x01)   /* Write to Status Register */

/* Status Register bits. */
#define	SR_WIP			0x01	         /* Write in progress */
#define	SR_WEL			0x02	         /* Write enable latch */

/* SPC300 SPI Controller registers */
#define  SPI_CTL_MASTER_SLAVE_REG      (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x00) )  )
#define  SPI_CTL_CONTROL_CONFIG_REG    (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x04) )  )
#define  SPI_CTL_FREQ_REG              (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x08) )  )
#define  SPI_CTL_CONF_TX               (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x10) )  )
#define  SPI_CTL_CONF_RX               (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x14) )  )
#define  SPI_CTL_CS_LATENCY            (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x18) )  )
#define  SPI_CTL_TX_REG                (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x20) )  )
#define  SPI_CTL_RX_REG                (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x24) )  )
#define  SPI_CTL_MASK_REG              (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x34) )  )
#define  SPI_CTL_STATUS_REG            (  *( (volatile unsigned int *)(CFG_FLASH_SPI_BASE + 0x38) )  )

#define SPI_CTL_FREQ_REG_VAL   ((CONFIG_CHIP_MAX_MASTER_CLOCK + CFG_SPI_FREQ * 2 - 1) \
                                / (CFG_SPI_FREQ * 2) - 1)

/* status bits */
enum
{
   EMPTY_FIFO_TX  =  0x01,
   FULL_FIFO_TX   =  0x02,
   EMPTY_FIFO_RX  =  0x04,
   FULL_FIFO_RX   =  0x08,
   RECEIVED_WORD  =  0x10,
   BUSY_MASTER    =  0x20
};

#define READY_SPI 0x00000001
#define ERR_SPI   0x00000002
#define TMO_SPI   0x00000004

typedef enum
{
    WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY = 0,
    WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY = 1,
    WAIT_RX_FIFO_NOT_EMPTY = 2,
    WAIT_TX_FIFO_NOT_FULL = 3,
    WAIT_RECEIVED_WORD = 4
} wait_status_t;

int ERROR_FLASH_SPI = 0;

int flash_read_status_spi(unsigned char *flash_spi_status);
int flash_read_id_spi(unsigned int *flash_spi_id);
int flash_real_protect (flash_info_t * info, long sector, int prot);

/* --- Utility functions --- */
static inline void swap_endians (int *in)
{
    *in = (
            (  (*in & 0xFF000000) >> 24   ) |
            (  (*in & 0x00FF0000) >> 8    ) |
            (  (*in & 0x0000FF00) << 8    ) |
            (  (*in & 0x000000FF) << 24   )
          );
}


static inline void seterr_flash_spi(int val)
{
   ERROR_FLASH_SPI = val;
}

static inline int wait_flash_ready(int tout)
{
    unsigned long nowtime;
    int chip1;
    int rc = ERR_OK;
    unsigned char flash_spi_status;

    nowtime = get_timer(0);
    chip1 = 0;
    do
    {

        if ( flash_read_status_spi(&flash_spi_status) == ERR_TIMOUT )
        {
            chip1 = TMO_SPI;
            break;
        }

        /* check timeout */
        if (get_timer(nowtime) > tout)
        {
            chip1 = TMO_SPI;
            break;
        } /* if */

        if ( !chip1 && ( (flash_spi_status & SR_WIP) == 0 ) )
        {
            chip1 = READY_SPI;
        }

    } while (!chip1); /* do ... while */

    if (chip1 == TMO_SPI)
    {
        seterr_flash_spi(ERR_TIMOUT);
        rc = ERR_TIMOUT;
    }
    //printf ("ok.\n");
    return rc;
}

static inline int wait_status(wait_status_t what)
{
    int mask = 0;   /* what bits we inspect */
    int cond = 0;  /* what we expect to stop looping */
    int rc = ERR_OK;
    unsigned long nowtime;

    switch (what)
    {
    case WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY:
        /* wait until Tx and Rx FIFOs become empty
           and SPI bus become not busy
           to be sure that no other transmissoin is in progress */
        mask = EMPTY_FIFO_TX | EMPTY_FIFO_RX | BUSY_MASTER ;    /* what bits we look */
        cond = EMPTY_FIFO_TX | EMPTY_FIFO_RX | 0;               /* we want empty FIFOs (set to "1") and not BUSY MASTER (i.e. set to "0") */
        break;
    case WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY:
        mask = EMPTY_FIFO_TX | BUSY_MASTER ;
        cond = EMPTY_FIFO_TX | 0;
        break;
    case WAIT_RX_FIFO_NOT_EMPTY:
        mask = EMPTY_FIFO_RX;
        cond = 0;
        break;
    case WAIT_TX_FIFO_NOT_FULL:
        /* wait until FIFO is not full (i.e. loop if it is full) */
        mask = FULL_FIFO_TX;
        cond = 0;
        break;
    case WAIT_RECEIVED_WORD:
        /* wait until we have receive something */
        mask = RECEIVED_WORD;
        cond = RECEIVED_WORD;
        break;
    } /* switch */

    nowtime = get_timer(0);

    /* poll until Tx and Rx FIFOs are empty
       and SPI bus is not busy
       to be sure that no other transmissoin is in progress */

    while ( ( SPI_CTL_STATUS_REG & mask ) != cond )
    {
        /* check timeout */
        if ( get_timer(nowtime) > SPI_CTL_TMO)
        {
            seterr_flash_spi(ERR_TIMOUT);
            return ERR_TIMOUT;
        } /* if */
    } /* while */

    return rc;
}

/* --- Drasiver functions --- */

/**
 * Function:     init_spi_controller
 * Parameters:
 * Purpose:      Initialize SPI controller to use SPI flash
 * Return Value: ushort
 */
void init_spi_controller(void)
{
   //printf("Initializing SPI controller...\n");

   SPI_CTL_MASTER_SLAVE_REG   =  0x01;          /* Master */
   SPI_CTL_CONTROL_CONFIG_REG =  0x00;          /* 3 wires Master */
   SPI_CTL_FREQ_REG           =  SPI_CTL_FREQ_REG_VAL;
   SPI_CTL_CS_LATENCY         =  0x04;          /* 4 cycles clock AHB */
   SPI_CTL_CONF_TX            =  0x00010008;    /* send one byte (i.e. one word of length of 8 bits) */
   SPI_CTL_CONF_RX            =  0x00010008;    /* receive one byte */
   SPI_CTL_MASK_REG           =  0x0;           /* mask all interrupts */
}


/**
 * Function:     flash_read_id_spi
 * Parameters:   none
 * Purpose:      Read flash id
 * Return Value: int
 */
int flash_read_id_spi(unsigned int *flash_spi_id)
{
   int rc = ERR_OK;
   int i;

   /* poll until Tx and Rx FIFOs are empty
      and SPI bus is not busy
      to be sure that no other transmission is in progress */
   if ( ( rc = wait_status(WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
   {
       return rc;
   }

   /* read spi flash status reg */
   SPI_CTL_CONF_TX = 0x00010008;    /* send one byte */
   SPI_CTL_CONF_RX = 0x00030008;    /* receive 3 bytes */
   /*issue the command to spi flash */
   SPI_CTL_TX_REG = RDID;

   /* flash spi status is now in SPI Controller Rx reg */
   *flash_spi_id = 0;
   for (i=0; i<3; i++)
   {
       if ( ( rc = wait_status(WAIT_RX_FIFO_NOT_EMPTY) ) == ERR_TIMOUT )
       {
           return rc;
       }
       *flash_spi_id = (*flash_spi_id << 8) | (SPI_CTL_RX_REG & 0xFF);
   }

   return rc;
}


/**
 * Function:     flash_spi_number_sector
 * Parameters:   OrgDef *pOrgDef, unsigned int nb_blocks
 * Purpose:      Determine the number of sector
 * Return Value: ushort
 */
ushort flash_number_sector_spi(OrgDef *pOrgDef, unsigned int nb_blocks)
{
	int i, nb_sectors = 0;

	for (i=0; i<nb_blocks; i++)
		nb_sectors += pOrgDef[i].sector_number;

	return nb_sectors;
} /* flash_number_sector_spi */

/**
 * Function:     flash_init
 * Parameters:   void
 * Purpose:      Init flash
 * Return Value: ulong
 */
ulong flash_init (void)
{
	int i, j, k;
	unsigned int flash_nb_blocks, sector;
	unsigned int start_address;
	OrgDef *pOrgDef;
    spc300_nvram_t *nvram = NULL;
    OrgDef OrgSPIFlash = {128, 64*1024};   /* init with default value */
    uint32_t flash_org;

	ulong size = 0;

    /* initialize our SPI controler */
    init_spi_controller();

    /* use parameters from nvram */
    nvram = (spc300_nvram_t *)(gd->bd->bi_nvram_addr);
    flash_org = nvram->flash_org;

    OrgSPIFlash.sector_number = 1 << NVRAM_BFEXT(FLASH_NB_SECT, flash_org);
    OrgSPIFlash.sector_size = (64*1024) * (NVRAM_BFEXT(FLASH_SECT_SZ, flash_org)+1);

    for (i = 0; i < CFG_MAX_FLASH_BANKS; i++)
    {
		ulong flashbase = 0;

		pOrgDef = &OrgSPIFlash;
		flash_nb_blocks = sizeof (OrgSPIFlash) / sizeof (OrgDef);

		flash_info[i].sector_count = flash_number_sector_spi(pOrgDef, flash_nb_blocks);
                flash_read_id_spi ((unsigned int *)&flash_info[i].flash_id);
		memset (flash_info[i].protect, 0, flash_info[i].sector_count);

                /* force unprotect for atmel flashs */
                if (IS_ATMEL_FLASH(flash_info[i].flash_id))
                    flash_real_protect (&flash_info[i], 0, 0);

		if (i == 0)
			flashbase = PHYS_FLASH_SPI_1;
		else
			panic ("configured too many flash banks!\n");

		sector = 0;
		start_address = flashbase;
		flash_info[i].size = 0;

		for (j = 0; j < flash_nb_blocks; j++)
        {
			for (k = 0; k < pOrgDef[j].sector_number; k++)
            {
				flash_info[i].start[sector++] = start_address;
				start_address += pOrgDef[j].sector_size;
				flash_info[i].size += pOrgDef[j].sector_size;
			}
		}

		size += flash_info[i].size;
	}

    return size;

} /* flash_init */

/**
 * Function:     flash_print_info
 * Parameters:   flash_info_t * info
 * Purpose:      Get flash info
 * Return Value: void
 */
void flash_print_info (flash_info_t * info)
{
	int i;

    printf ("FLASH SPI (Jedec=%#x)", info->flash_id);

	printf ("  Size: %ld MB in %d Sectors\n",
		info->size >> 20, info->sector_count);

	printf ("  Sector Start Addresses:");
	for (i = 0; i < info->sector_count; i++) {
		if ((i % 5) == 0) {
			printf ("\n   ");
		}
		printf (" %08lX%s", info->start[i],
			info->protect[i] ? " (RO)" : "     ");
	}
	printf ("\n");
} /* flash_print_info */

/**
 * Function:     flash_read_status_spi
 * Parameters:   unsigned char *flash_spi_status
 * Purpose:      read from flash status register
 * Return Value: int
 */
int flash_read_status_spi(unsigned char *flash_spi_status)
{
    int rc = ERR_OK;

    /* poll until Tx and Rx FIFOs are empty
       and SPI bus is not busy
       to be sure that no other transmissoin is in progress */
    if ( ( rc = wait_status(WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
    {
        return rc;
    }

    /* read spi flash status reg */
    SPI_CTL_CONF_TX = 0x00010008;    /* send one byte */
    SPI_CTL_CONF_RX = 0x00010008;    /* receive one byte */
    /*issue the command to spi flash */
    SPI_CTL_TX_REG = RDSR;

    /* busy wait for RECEIVED_WORD bit in status reg */
    if ( ( rc = wait_status(WAIT_RECEIVED_WORD) != ERR_OK ) )
    {
        return rc;
    }

    /* flash spi status is now in SPI Controller Rx reg */
    *flash_spi_status = SPI_CTL_RX_REG;

    return rc;
}


/**
 * Function:     flash_write_enable_spi
 * Parameters:   int s_first, int s_last
 * Purpose:      WREN command to the SPI Flash
 * Return Value: int
 */
int flash_write_enable_spi (void)
{
    int rc = ERR_OK;

    /* poll until Tx FIFO is empty
       and SPI bus is not busy
       to be sure that no other transmissoin is in progress */
    if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
    {
        return rc;
    }

    /* write enable spi flash */
    SPI_CTL_CONF_TX = 0x00010008;    /* send one byte (just command) */
    /* reset SPI_CTL_CONF_RX - no bytes expected to be received.
       This step is needed because it will not be
       auto-reset from the previous operaton */
    SPI_CTL_CONF_RX = 0x00000008;
    /*issue the command to spi flash */
    SPI_CTL_TX_REG = WREN;

    /* poll until Tx FIFO is empty
       and SPI bus is not busy
       to be sure that our transmission finished */
    if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
    {
        return rc;
    }

    return rc;
}

/**
 * Function:     flash_erase
 * Parameters:   int s_first, int s_last
 * Purpose:      Erase flash
 * Return Value: int
 */
int flash_erase (flash_info_t * info, int s_first, int s_last)
{
	int sect;
	int rc = ERR_OK;
    int erase_flash_spi_command = 0;

	if ((s_first < 0) || (s_first > s_last))
    {
		seterr_flash_spi(ERR_INVAL);
		return ERR_INVAL;
	} /* if */


	/* Start erase on unprotected sectors */
    for (sect = s_first; sect <= s_last && !ctrlc (); sect++)
    {
		printf ("Erasing sector %2d ... ", sect);

		if (info->protect[sect] == 0)
        {
            /* not protected */
			volatile unsigned char *addr = (volatile unsigned char *) (info->start[sect]);

            /* mask MSB byte, i.e. set it to all-zero */
            addr = (volatile unsigned char *) ( (unsigned int)addr & ~(0xFF << 24) );
            erase_flash_spi_command = SE<<24 | (unsigned int)addr;

            swap_endians(&erase_flash_spi_command);

            /* before erase we have to write-enable SPI flash */
            if ( flash_write_enable_spi() == ERR_TIMOUT )
            {
                printf ("Cannot write-enable SPI flash.\n");
                seterr_flash_spi(ERR_TIMOUT);
                rc = ERR_TIMOUT;
                goto outahere;
            }

            /* poll until Tx FIFO is empty
               and SPI bus is not busy
               to be sure that no other transmissions are in progress */
            if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
            {
                goto outahere;
            }
            /* start command SPI controller seqence */
            SPI_CTL_CONF_TX = 0x00010020;    /* send 32 bit message (command + address) */
            /* reset SPI_CTL_CONF_RX - no bytes expected to be received.
            This step is needed because it will not be
            auto-reset from the previous operaton */
            SPI_CTL_CONF_RX = 0x00000000;
            /*issue the command to spi flash */
            SPI_CTL_TX_REG = erase_flash_spi_command; /* send command + address to SPI flash via SPI controller */

            /* poll until Tx FIFO is empty
               and SPI bus is not busy
               to be sure that our transmission finished
            */
            if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
            {
                goto outahere;
            }

            /* Wait until flash is ready. */
            if ( ( rc = wait_flash_ready(CFG_FLASH_SPI_ERASE_TOUT) ) != ERR_OK)
            {
                goto outahere;
            }
            printf ("ok.\n");
		}
        else
        {	/* it was protected */
			printf ("protected!\n");
		} /* if */
	} /* for */

	if (ctrlc ())
		printf ("User Interrupt!\n");

outahere:
	return rc;
} /* flash_erase_std */



/**
 * Function:     flash_read_spi
 * Parameters:   volatile unsigned char *dst, unsigned char *tmp_buf, int length
 * Purpose:      Read SPI flash
 * Return Value: int
 */
int flash_read_spi (volatile unsigned char *gl_addr, volatile unsigned char *data, int length, int dirty_flag, int do_cmp)
{
	int rc = ERR_OK;
    unsigned int tx_conf, rx_conf, rx_max_words, bytes_to_read;
    unsigned int nb_read = 0;   /* number of read words */
    int i=0;
    unsigned int result;
    int error_flag = 0;
    //unsigned int kprint = 0;
    volatile unsigned char *addr;

    /* Whatever the address, only offset is important */
    addr = (volatile unsigned char*)(((unsigned int)(gl_addr)) & 0x00FFFFFF);
#ifdef DEBUG_FLASH_SPI
        printf("addr = %#x\n", addr);
#endif

    /* maximum number of bytes that SPI controller
      can receive in one go is size of RX FIFO - 8 bytes */
    rx_max_words = 0xffff;

    while ( nb_read < length)
    {
        /* set tx_conf */
        tx_conf = (0x4 << 16) | 0x08;   /* 1 byte for command and 3 bytes for addr */

        /* set rx_conf */
        if ( (length - nb_read) > rx_max_words )
        {
            rx_conf = (rx_max_words << 16) | 0x08;
            bytes_to_read = rx_max_words;
        }
        else
        {
            rx_conf = ( (length - nb_read) << 16 ) | 0x08;
            bytes_to_read = length - nb_read;
        }

        /* wait untill SPI is ready for transaction */
        if ( ( rc = wait_status(WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY) ) == ERR_TIMOUT )
        {
            goto outahere;
        }

#ifdef DEBUG_FLASH_SPI
        printf("tx_conf = %#x\n", tx_conf);
        printf("rx_conf = %#x\n", rx_conf);
#endif

        /* configure how many bytes to send/receive */
        SPI_CTL_CONF_TX = tx_conf;
        SPI_CTL_CONF_RX = rx_conf;

        if ( ( rc = wait_status(WAIT_TX_FIFO_NOT_FULL) ) == ERR_TIMOUT )
        {
            goto outahere;
        }
        SPI_CTL_TX_REG = READ; /* send command to SPI flash via SPI controller */

        for (i=2; i>=0; i--)
        {
            if ( ( rc = wait_status(WAIT_TX_FIFO_NOT_FULL) ) == ERR_TIMOUT )
            {
                printf("%s: Error sending the address to SPI controller", __FUNCTION__);
                goto outahere;
            }
            /* send address to SPI flash via SPI controller */
            SPI_CTL_TX_REG = ( (unsigned int)(addr + nb_read) >> i*8 ) & 0xff ;
        }

        /* and now receive the data */
        for (i=0; i<bytes_to_read; i++)
        {
            if ( ( rc = wait_status(WAIT_RX_FIFO_NOT_EMPTY) ) == ERR_TIMOUT )
            {
                goto outahere;
            }
            result = SPI_CTL_RX_REG;

            if (do_cmp)
            {
                /*
                 * do_cmp == 1 => flash_read_spi() was called from write_buff(),
                 * and result read should be either all 1 (if flash is clean)
                 * or what was in data[] given to the function
                 */

                /* Check the result for errors.
                If there has been an error we can not go out emmidiately,
                we must wait SPI controller to finish transsaction,
                because we configured rx_config, and cannot repprogram it in the
                middle of transaction */
                if (dirty_flag == 0)
                {
                    if  ( ( result & data[nb_read] )  !=  data[nb_read] )
                    {
                        error_flag = 1;
                        rc = ERR_NOT_ERASED;
                    }

                }
                else  /* flash is dirty (written to) */
                {
                    if ( result != data[nb_read])
                    {
                        error_flag = 1;
                        rc = ERR_PROG_ERROR;
                    }
                }
            }
            else /* do_cmp == 0 */
            {
                /* flash was not called from write_buff(),
                 * that means it was not called in compare purposes,
                 * but we really want to retreive data.
                 * So we will set data[nb_read] to appropriate value
                 */
                /* we can read whole integer into dest addr, because it is on word boundary */
                data[nb_read] = result;
            }

            /* OK, go to the next byte */
            nb_read ++;

        } /* for */
#if 0
        /* print output to user to know that writing is in progress. */
        if(kprint && (kprint*nb_read % 0xffffff == 0))
            puts("#");
        kprint ++;
#endif

    } /* while */

outahere:
    return rc;
}

/**
 * Function:     flash_real_protect
 * Parameters:   flash_info_t * info, long sector, int prot
 * Purpose:      Protect/unprotect the flash from writing
 * Return Value: int
 */
int flash_real_protect (flash_info_t * info, long sector, int prot)
{
    int rc = 0;
    int i;
    unsigned short protect_command;

    if (IS_ATMEL_FLASH(info->flash_id))
    {
        /* before erase we have to write-enable SPI flash */
        if ( flash_write_enable_spi() == ERR_TIMOUT )
        {
            printf ("Cannot write-enable SPI flash.\n");
            seterr_flash_spi(ERR_TIMOUT);
            rc = ERR_TIMOUT;
            return rc;
        }
        /* protection is done on all the flash */
        /* poll until Tx FIFO is empty
           and SPI bus is not busy
           to be sure that no other transmissions are in progress */
        if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
        {
            return rc;
        }

        protect_command = ((prot ? 0x3f : 0x00) << 8) | WRSR;
        /* start command SPI controller seqence */
        SPI_CTL_CONF_TX = 0x00010010;    /* send 32 bit message (command + address) */
        /* reset SPI_CTL_CONF_RX - no bytes expected to be received.
           This step is needed because it will not be
           auto-reset from the previous operaton */
        SPI_CTL_CONF_RX = 0x00000000;
        /*issue the command to spi flash */
        SPI_CTL_TX_REG = protect_command; /* send protect */
        if ( ( rc = wait_status(WAIT_TX_FIFO_EMPTY_AND_NOT_BUSY) != ERR_OK ) )
        {
            return rc;
        }

        /* protect on/off is put on all the flash */
        for (i = 0; i < info->sector_count; i++) {
            info->protect[i] = prot;
        }
    }

    info->protect[sector] = prot;

    return rc;
}

/**
 * Function:     write_buff
 * Parameters:   flash_info_t * info, uchar * src, ulong addr, ulong cnt
 * Purpose:      Write buffer
 * Return Value: int
 */
int write_buff (flash_info_t * info, uchar * src, ulong dest, ulong cnt)
{
    volatile unsigned char *data = (volatile unsigned char *) src;
    volatile unsigned char *addr = (volatile unsigned char*)(((unsigned int)(dest)) & 0x00FFFFFF);
	int length = cnt;
    unsigned int kprint = 0;
	int rc = ERR_OK;
    int i=0;
    int nb_written = 0;
    unsigned int tx_max_bytes, bytes_to_write;
    unsigned int tx_conf, rx_conf;
    unsigned int cur_addr;

    /*
	 * Check if Flash is (sufficiently) erased
	 */
    /* call to SPI flash READ function with drty_flag = 0 */
    if ( ( rc = flash_read_spi (addr, data, length, 0, 1) ) != ERR_OK )
    {
        seterr_flash_spi(rc);
        goto outahere;
    }

    /* reset length wor WRITE operation */
    length = cnt;

    /* maximum of bytes that our SPI Flash
       can write in one go is 256,
       if we start on 256 boundary.
       It is because the write that begun within one 256 byte region must finish
       in the same region in order for addresses to be well written  */
    tx_max_bytes = 0x100 - 1 - 3;   /* bytes of data, without 1 byte needed for command and 3 for addr */

    while (nb_written < length)
    {
        if ( (length - nb_written) > tx_max_bytes )
        {
            tx_conf =   ( (tx_max_bytes + 1 + 3) << 16 ) | 0x8;
            bytes_to_write = tx_max_bytes;
        }
        else
        {
            tx_conf = ( (1 + 3 + (length - nb_written) ) << 16 ) | 0x8;
            bytes_to_write = length - nb_written;
        }

        /* configure rx */
        rx_conf =   (0 << 16) | 0x8;

        /* Check if we will do writing within same 256 byte region.
           It is not allowed to cross to next region within same PP operation.
           If we are crossing to the next region, lower the bytes_to_write,
           in order to finish writing on 256 byte region boundary (i.e. to do all
           the writing in the same region in which we are starting). */
        cur_addr = (unsigned int)(addr + nb_written);
        if ( (cur_addr % 256) + bytes_to_write > 256)
        {
            bytes_to_write =  256 - (cur_addr % 256) ;
            tx_conf = (bytes_to_write + 1 + 3) << 16 | 0x08;
        }

        /* First write-enable the SPI flash */
        if ( flash_write_enable_spi() == ERR_TIMOUT )
        {
            printf ("Cannot write-enable SPI flash\n");
            seterr_flash_spi(ERR_TIMOUT);
            rc = ERR_TIMOUT;
            goto outahere;
        }

        /* And then program flash */
        if ( ( rc = wait_status(WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY) ) == ERR_TIMOUT )
        {
            goto outahere;
        }

        SPI_CTL_CONF_TX = tx_conf;    /* send 32 bit message (command + address) */
        SPI_CTL_CONF_RX = rx_conf;

        if ( ( rc = wait_status(WAIT_TX_FIFO_NOT_FULL) ) == ERR_TIMOUT )
        {
            goto outahere;
        }
        SPI_CTL_TX_REG = PP;

        for (i=2; i>=0; i--)
        {
            if ( ( rc = wait_status(WAIT_TX_FIFO_NOT_FULL) ) == ERR_TIMOUT )
            {
                goto outahere;
            }
            SPI_CTL_TX_REG =  (cur_addr >> i*8) & 0xff;
        }

#ifdef DEBUG_FLASH_SPI
        printf("tx_conf = %#x\n", tx_conf);
        printf("rx_conf = %#x\n", rx_conf);
#endif

        /* now write the data */
        for (i=0; i < bytes_to_write; i++)
        {
            if ( ( rc = wait_status(WAIT_TX_FIFO_NOT_FULL) ) == ERR_TIMOUT )
            {
                goto outahere;
            }

            SPI_CTL_TX_REG = data[nb_written];

            nb_written++;

        } /* for */

        /* print output to user to know that writing is in progress.
               On every 256*256b written print "." */
        if(kprint && (kprint % 256 == 0))
            puts(".");
        kprint ++;

        if ( ( rc = wait_status(WAIT_ALL_FIFO_EMPTY_AND_NOT_BUSY) ) == ERR_TIMOUT )
        {
            goto outahere;
        }

        /* Wait until flash is ready. */
        if ( ( rc = wait_flash_ready(CFG_FLASH_SPI_WRITE_TOUT) ) != ERR_OK)
        {
            goto outahere;
        }
    } /* while */

    /*
     * read the data to verify the write
     */
    /* call to SPI flash READ function with drty_flag = 1 */
    if ( ( rc = flash_read_spi (addr, data, length, 1, 1) ) != ERR_OK )
    {
        seterr_flash_spi(rc);
        goto outahere;
    } /* if */
    putc(' ');

outahere:
	return rc;
} /* write_buf */