Home | History | Annotate | Line # | Download | only in ebus
      1 /*	$NetBSD: flash_ebus.c,v 1.26 2026/05/29 14:39:01 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2010 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code was written by Alessandro Forin and Neil Pittman
      8  * at Microsoft Research and contributed to The NetBSD Foundation
      9  * by Microsoft Corporation.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>			/* RCS ID & Copyright macro defns */
     34 __KERNEL_RCSID(0, "$NetBSD: flash_ebus.c,v 1.26 2026/05/29 14:39:01 thorpej Exp $");
     35 
     36 /* Driver for the Intel 28F320/640/128 (J3A150) StrataFlash memory device
     37  * Extended to include the Intel JS28F256P30T95.
     38  */
     39 
     40 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/kernel.h>
     43 #include <sys/proc.h>
     44 #include <sys/errno.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/device.h>
     47 #include <sys/conf.h>
     48 #include <sys/file.h>
     49 #include <sys/stat.h>
     50 #include <sys/ioctl.h>
     51 #include <sys/buf.h>
     52 #include <sys/bufq.h>
     53 #include <sys/uio.h>
     54 #include <uvm/uvm_extern.h>
     55 #include <sys/disklabel.h>
     56 #include <sys/disk.h>
     57 #include <sys/syslog.h>
     58 #include <sys/vnode.h>
     59 #include <sys/kthread.h>
     60 #include <sys/lock.h>
     61 #include <sys/queue.h>
     62 
     63 #include <sys/rndsource.h>
     64 
     65 #include "locators.h"
     66 #include <prop/proplib.h>
     67 
     68 #include <emips/ebus/ebusvar.h>
     69 #include <emips/emips/machdep.h>
     70 #include <machine/emipsreg.h>
     71 
     72 /* Internal config switches
     73  */
     74 #define USE_BUFFERED_WRITES 0    /* Faster, but might not work in some (older) cases */
     75 #define Verbose 0
     76 
     77 /* Debug tools
     78  */
     79 #define DEBUG_INTR   0x01
     80 #define DEBUG_XFERS  0x02
     81 #define DEBUG_STATUS 0x04
     82 #define DEBUG_FUNCS  0x08
     83 #define DEBUG_PROBE  0x10
     84 #define DEBUG_WRITES 0x20
     85 #define DEBUG_READS  0x40
     86 #define DEBUG_ERRORS 0x80
     87 #ifdef DEBUG
     88 int eflash_debug = DEBUG_ERRORS;
     89 #define EFLASH_DEBUG(x) (eflash_debug & (x))
     90 #define DBGME(_lev_,_x_) if ((_lev_) & eflash_debug) _x_
     91 #else
     92 #define EFLASH_DEBUG(x) (0)
     93 #define DBGME(_lev_,_x_)
     94 #endif
     95 #define DEBUG_PRINT(_args_,_lev_) DBGME(_lev_,printf _args_)
     96 
     97 /* Product ID codes
     98  */
     99 #define MANUF_INTEL  0x89
    100 #define DEVICE_320   0x16
    101 #define DEVICE_640   0x17
    102 #define DEVICE_128   0x18
    103 #define DEVICE_256   0x19
    104 
    105 /* Table of chips we understand.
    106  */
    107 #define nDELTAS 3
    108 struct flash_type {
    109     struct {
    110         uint32_t nSectors;
    111         uint32_t nKB;
    112     } ft_deltas[nDELTAS];
    113     uint8_t ft_manuf_code;
    114     uint8_t ft_device_code;
    115     uint16_t ft_total_sectors;
    116     const char *ft_name;
    117 };
    118 
    119 static const struct flash_type sector_maps[] = {
    120     {
    121      {{32,128},{0,0},},
    122      MANUF_INTEL, DEVICE_320, 32,   /* a J3 part */
    123      "StrataFlash 28F320"
    124     },
    125     {
    126      {{64,128},{0,0},},
    127      MANUF_INTEL, DEVICE_640, 64,   /* a J3 part */
    128      "StrataFlash 28F640"
    129     },
    130     {
    131      {{128,128},{0,0},},
    132      MANUF_INTEL, DEVICE_128, 128,   /* a J3 part */
    133      "StrataFlash 28F128"
    134     },
    135     {
    136      {{255,128},{4,32},{0,0}},
    137      MANUF_INTEL, DEVICE_256, 259,  /* a P30 part */
    138 	 "StrataFlash 28F256"
    139     }
    140 };
    141 #define nMAPS ((sizeof sector_maps) / (sizeof sector_maps[0]))
    142 
    143 /* Instead of dragging in atavar.h.. */
    144 struct eflash_bio {
    145 	volatile int flags;/* cmd flags */
    146 #define	ATA_POLL	0x0002	/* poll for completion */
    147 #define	ATA_SINGLE	0x0008	/* transfer must be done in singlesector mode */
    148 #define	ATA_READ	0x0020	/* transfer is a read (otherwise a write) */
    149 #define	ATA_CORR	0x0040	/* transfer had a corrected error */
    150 	daddr_t		blkno;	/* block addr */
    151 	daddr_t		blkdone;/* number of blks transferred */
    152 	size_t		nblks;	/* number of blocks currently transferring */
    153 	size_t	    nbytes;	/* number of bytes currently transferring */
    154 	char		*databuf;/* data buffer address */
    155 	volatile int	error;
    156 	u_int32_t	r_error;/* copy of status register */
    157 };
    158 /* End of atavar.h*/
    159 
    160 /* chip-specific functions
    161  */
    162 struct flash_ops;
    163 
    164 /*
    165  * Device softc
    166  */
    167 struct eflash_softc {
    168 	device_t sc_dev;
    169 
    170 	/* General disk infos */
    171 	struct disk sc_dk;
    172 	struct bufq_state *sc_q;
    173 	struct callout sc_restart_ch;
    174 
    175 	/* IDE disk soft states */
    176 	struct buf *sc_bp; /* buf being transferred */
    177 	struct buf *active_xfer; /* buf handoff to thread  */
    178 	struct eflash_bio sc_bio; /* current transfer */
    179 
    180     struct proc *ch_thread;
    181     int ch_flags;
    182 #define ATACH_SHUTDOWN 0x02        /* thread is shutting down */
    183 #define ATACH_IRQ_WAIT 0x10        /* thread is waiting for irq */
    184 #define ATACH_DISABLED 0x80        /* channel is disabled */
    185 #define ATACH_TH_RUN   0x100       /* the kernel thread is working */
    186 #define ATACH_TH_RESET 0x200       /* someone ask the thread to reset */
    187 
    188 	int openings;
    189 	int sc_flags;
    190 #define	EFLASHF_WLABEL	0x004 /* label is writable */
    191 #define	EFLASHF_LABELLING	0x008 /* writing label */
    192 #define EFLASHF_LOADED	0x010 /* parameters loaded */
    193 #define EFLASHF_WAIT	0x020 /* waiting for resources */
    194 #define EFLASHF_KLABEL	0x080 /* retain label after 'full' close */
    195 
    196 	int retries; /* number of xfer retry */
    197 
    198 	krndsource_t	rnd_source;
    199 
    200     /* flash-specific state */
    201 	struct _Flash *sc_dp;
    202     uint32_t sc_size;
    203     uint32_t sc_capacity;
    204     paddr_t  sc_base;
    205     volatile uint8_t *sc_page0;
    206 
    207     /* current read-write sector mapping */
    208     /*volatile*/ uint8_t *sc_sector;
    209     uint32_t sc_sector_size;
    210     uint32_t sc_sector_offset;
    211 #define NOSECTOR ((uint32_t)(~0))
    212     int sc_erased;
    213 
    214     /* device-specificity */
    215     uint32_t sc_buffersize;
    216     vsize_t sc_max_secsize;
    217     unsigned int sc_chips;
    218     const struct flash_ops *sc_ops;
    219     struct flash_type sc_type;
    220 };
    221 
    222 static int	eflash_ebus_match (device_t, cfdata_t, void *);
    223 static void	eflash_ebus_attach (device_t, device_t, void *);
    224 
    225 CFATTACH_DECL_NEW(flash_ebus, sizeof (struct eflash_softc),
    226     eflash_ebus_match, eflash_ebus_attach, NULL, NULL);
    227 
    228 /* implementation decls */
    229 static int flash_identify(struct eflash_softc*);
    230 static int KBinSector(struct flash_type * SecMap, unsigned int SecNo);
    231 static uint32_t SectorStart(struct flash_type * SecMap, int SecNo);
    232 static unsigned int SectorNumber(struct flash_type * SecMap, uint32_t Offset);
    233 static void eflash_thread(void *arg);
    234 static int eflash_read_at (struct eflash_softc *sc, daddr_t start_sector, char *buffer,
    235                            size_t nblocks, size_t * pSizeRead);
    236 static int eflash_write_at(struct eflash_softc *sc, daddr_t start_sector, char *buffer,
    237                            size_t nblocks, size_t * pSizeWritten);
    238 
    239 /* Config functions
    240  */
    241 static int
    242 eflash_ebus_match(device_t parent, cfdata_t match, void *aux)
    243 {
    244 	struct ebus_attach_args *ia = aux;
    245 	struct _Flash *f = (struct _Flash *)ia->ia_vaddr;
    246 
    247 	if (strcmp("flash", ia->ia_name) != 0)
    248 		return (0);
    249 	if ((f == NULL) ||
    250 	    ((f->BaseAddressAndTag & FLASHBT_TAG) != PMTTAG_FLASH))
    251 		return (0);
    252 
    253 	return (1);
    254 }
    255 
    256 static void
    257 eflash_ebus_attach(device_t parent, device_t self, void *aux)
    258 {
    259 	struct ebus_attach_args *ia =aux;
    260 	struct eflash_softc *sc = device_private(self);
    261     uint32_t base, ctrl;
    262     int error;
    263 
    264     /* Plan.
    265      * - mips_map_physmem() (with uncached) first page
    266      * - keep it around since we need status ops
    267      * - find what type it is.
    268      * - then mips_map_physmem() each sector as needed.
    269      */
    270 
    271 	sc->sc_dev = self;
    272 	sc->sc_dp = (struct _Flash*)ia->ia_vaddr;
    273     base = sc->sc_dp->BaseAddressAndTag & FLASHBT_BASE;
    274     ctrl = sc->sc_dp->Control;
    275 
    276     sc->sc_size = ctrl & FLASHST_SIZE;
    277     sc->sc_capacity = sc->sc_size / DEV_BSIZE;
    278     sc->sc_base = base;
    279     /* The chip is 16bit, so if we get 32bit there are two */
    280     sc->sc_chips = (ctrl & FLASHST_BUS_32) ? 2 : 1;
    281 
    282     /* Map the first page to see what chip we got */
    283     sc->sc_page0 = (volatile uint8_t *) mips_map_physmem(base, PAGE_SIZE);
    284 
    285     if (flash_identify(sc)) {
    286         printf(" base %x: %dMB flash memory (%d x %s)\n", base, sc->sc_size >> 20,
    287                sc->sc_chips, sc->sc_type.ft_name);
    288     } else {
    289         /* BUGBUG If we dont identify it stop the driver! */
    290         printf(": unknown manufacturer id %x, device id %x\n",
    291                sc->sc_type.ft_manuf_code, sc->sc_type.ft_device_code);
    292     }
    293 
    294     config_pending_incr(self);
    295 
    296 	error = kthread_create(PRI_NONE, 0, NULL,
    297 	    eflash_thread, sc, NULL, "%s", device_xname(sc->sc_dev));
    298 	if (error)
    299 		aprint_error_dev(sc->sc_dev,
    300 		    "unable to create kernel thread: error %d\n", error);
    301 }
    302 
    303 /* Implementation functions
    304  */
    305 /* Returns the size in KBytes of a given sector,
    306  * or -1 for bad arguments.
    307  */
    308 static int KBinSector(struct flash_type * SecMap, unsigned int SecNo)
    309 {
    310     int i;
    311 
    312     for (i = 0; i < nDELTAS; i++) {
    313         if (SecNo < SecMap->ft_deltas[i].nSectors)
    314             return SecMap->ft_deltas[i].nKB;
    315         SecNo -= SecMap->ft_deltas[i].nSectors;
    316     }
    317 
    318     return -1;
    319 }
    320 
    321 #define SectorSize(_map_,_sector_) (1024 * KBinSector(_map_,_sector_))
    322 
    323 /* Whats the starting offset of sector N
    324  */
    325 static uint32_t SectorStart(struct flash_type * SecMap, int SecNo)
    326 {
    327     int i;
    328     uint32_t Offset = 0;
    329 
    330     for (i = 0; i < nDELTAS; i++) {
    331         if ((unsigned int)SecNo < SecMap->ft_deltas[i].nSectors)
    332             return 1024 * (Offset + (SecMap->ft_deltas[i].nKB * SecNo));
    333         SecNo -= SecMap->ft_deltas[i].nSectors;
    334         Offset += SecMap->ft_deltas[i].nSectors * SecMap->ft_deltas[i].nKB;
    335     }
    336 
    337     return ~0;
    338 }
    339 
    340 /* What sector number corresponds to a given offset
    341  */
    342 static unsigned int SectorNumber(struct flash_type * SecMap, uint32_t Offset)
    343 {
    344     unsigned int i;
    345     unsigned int SecNo = 0;
    346 
    347     Offset /= 1024;
    348     for (i = 0; i < nDELTAS; i++) {
    349         if (Offset < (unsigned int)
    350             ((SecMap->ft_deltas[i].nSectors * SecMap->ft_deltas[i].nKB)))
    351             return SecNo + (Offset / SecMap->ft_deltas[i].nKB);
    352         SecNo += SecMap->ft_deltas[i].nSectors;
    353         Offset -= SecMap->ft_deltas[i].nSectors * SecMap->ft_deltas[i].nKB;
    354     }
    355 
    356     return ~0;
    357 }
    358 
    359 /*
    360  * Semi-generic operations
    361  */
    362 struct flash_ops {
    363     void (*write_uint8)    (struct eflash_softc *sc, volatile void *Offset, uint8_t Value);
    364     void (*read_uint8)     (struct eflash_softc *sc, volatile void *Offset, uint8_t *Value);
    365     void (*write_uint16)   (struct eflash_softc *sc, volatile void *Offset, uint16_t Value);
    366     void (*read_uint16)    (struct eflash_softc *sc, volatile void *Offset, uint16_t *Value);
    367     void (*write_uint32)   (struct eflash_softc *sc, volatile void *Offset, uint32_t Value);
    368     void (*read_uint32)    (struct eflash_softc *sc, volatile void *Offset, uint32_t *Value);
    369     int  (*program_word)   (struct eflash_softc *sc, volatile void *Offset, uint16_t *pValues,
    370                             int  Verify, int *nWritten);
    371     int  (*program_buffer) (struct eflash_softc *sc, volatile void *Offset, uint16_t *pValues,
    372                             int  Verify, int *nWritten);
    373 };
    374 
    375 /*
    376  * Hardware access proper, single-chip
    377  */
    378 static void single_write_uint8  (struct eflash_softc *sc,volatile void *Offset,uint8_t Value)
    379 {
    380     volatile uint8_t * Where = Offset;
    381     *Where = Value;
    382 }
    383 
    384 static void single_read_uint8   (struct eflash_softc *sc,volatile void *Offset,uint8_t *Value)
    385 {
    386     volatile uint8_t * Where = Offset;
    387     *Value = *Where;
    388 }
    389 
    390 static void single_write_uint16 (struct eflash_softc *sc,volatile void *Offset,uint16_t Value)
    391 {
    392     volatile uint16_t * Where = Offset;
    393     *Where = Value;
    394 }
    395 
    396 static void single_read_uint16  (struct eflash_softc *sc,volatile void *Offset,uint16_t *Value)
    397 {
    398     volatile uint16_t * Where = Offset;
    399     *Value = *Where;
    400 }
    401 
    402 /* This one should not be used, probably */
    403 static void single_write_uint32 (struct eflash_softc *sc,volatile void *Offset,uint32_t Value)
    404 {
    405 #if 0
    406     /* The chip cannot take back-to-back writes */
    407     volatile uint32_t * Where = Offset;
    408     *Where = Value;
    409 #else
    410     volatile uint8_t * Where = Offset;
    411     uint16_t v0, v1;
    412 
    413     /* Unfortunately, this is bytesex dependent */
    414 #if (BYTE_ORDER == BIG_ENDIAN)
    415     v1 = (uint16_t) Value;
    416     v0 = (uint16_t) (Value >> 16);
    417 #else
    418     v0 = (uint16_t) Value;
    419     v1 = (uint16_t) (Value >> 16);
    420 #endif
    421     single_write_uint16(sc,Where,v0);
    422     single_write_uint16(sc,Where+2,v1);
    423 #endif
    424 }
    425 
    426 static void single_read_uint32  (struct eflash_softc *sc,volatile void *Offset,uint32_t *Value)
    427 {
    428     /* back-to-back reads must be ok */
    429     volatile uint32_t * Where = Offset;
    430     *Value = *Where;
    431 }
    432 
    433 /*
    434  * Hardware access proper, paired-chips
    435  * NB: This set of ops assumes two chips in parallel on a 32bit bus,
    436  *     each operation is repeated in parallel to both chips
    437  */
    438 static void twin_write_uint8  (struct eflash_softc *sc,volatile void *Offset,uint8_t Value)
    439 {
    440     volatile uint32_t * Where = Offset;
    441     uint32_t v = Value | ((uint32_t)Value << 16);
    442 
    443     v = le32toh(v);
    444     *Where = v;
    445 }
    446 
    447 static void twin_read_uint8   (struct eflash_softc *sc,volatile void *Offset,uint8_t *Value)
    448 {
    449     volatile uint32_t * Where = Offset;
    450     uint32_t v;
    451     v = *Where;
    452     v = le32toh(v);
    453     *Value = (uint8_t) v;
    454 }
    455 
    456 /* This one should *not* be used, error-prone */
    457 static void twin_write_uint16 (struct eflash_softc *sc,volatile void *Offset,uint16_t Value)
    458 {
    459     volatile uint16_t * Where = Offset;
    460     *Where = Value;
    461 }
    462 
    463 static void twin_read_uint16  (struct eflash_softc *sc,volatile void *Offset,uint16_t *Value)
    464 {
    465     volatile uint16_t * Where = Offset;
    466     *Value = *Where;
    467 }
    468 
    469 static void twin_write_uint32 (struct eflash_softc *sc,volatile void *Offset,uint32_t Value)
    470 {
    471     volatile uint32_t * Where = Offset;
    472     Value = le32toh(Value);
    473     *Where = Value;
    474 }
    475 
    476 static void twin_read_uint32  (struct eflash_softc *sc,volatile void *Offset,uint32_t *Value)
    477 {
    478     volatile uint32_t * Where = Offset;
    479     uint32_t v;
    480     v = *Where;
    481     v = le32toh(v);
    482     *Value = v;
    483 }
    484 
    485 /*
    486  * Command and status definitions
    487  */
    488 
    489 /* Defines for the STATUS register
    490  */
    491 #define ST_reserved          0x01
    492 #define ST_BLOCK_LOCKED      0x02
    493 #define ST_PROGRAM_SUSPENDED 0x04
    494 #define ST_LOW_VOLTAGE       0x08
    495 #define ST_LOCK_BIT_ERROR    0x10
    496 #define ST_ERASE_ERROR       0x20
    497 #define ST_ERASE_SUSPENDED   0x40
    498 #define ST_READY             0x80
    499 #define ST_ERASE_MASK        0xee  /* bits to check after erase command */
    500 #define ST_MASK              0xfe  /* ignore reserved */
    501 
    502 /* Command set (what we use of it)
    503  */
    504 #define CMD_CONFIRM       0xd0
    505 #define CMD_READ_ARRAY    0xff
    506 #define CMD_READ_ID       0x90
    507 #define CMD_READ_STATUS   0x70
    508 #define CMD_CLEAR_STATUS  0x50
    509 #define CMD_WRITE_WORD    0x40
    510 #define CMD_WRITE_BUFFER  0xe8
    511 #define CMD_ERASE_SETUP   0x20
    512 #define CMD_ERASE_CONFIRM CMD_CONFIRM
    513 #define CMD_SET_PREFIX    0x60  /* set read config, lock bits */
    514 #define CMD_LOCK          0x01
    515 #define CMD_UNLOCK        CMD_CONFIRM
    516 /* What we dont use of it
    517  */
    518 #define CMD_READ_QUERY    0x98
    519 # define BUFFER_BYTES          32
    520 #define CMD_ERASE_SUSPEND 0xb0
    521 #define CMD_ERASE_RESUME  CMD_CONFIRM
    522 #define CMD_CONFIGURATION 0xb8
    523 #define CMD_PROTECT       0xc0
    524 
    525 /* Enter the Product ID mode (Read Identifier Codes)
    526  */
    527 static void ProductIdEnter(struct eflash_softc *sc)
    528 {
    529     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_READ_ID);
    530 }
    531 
    532 /* Exit the Product ID mode (enter Read Array mode)
    533  */
    534 static void ProductIdExit(struct eflash_softc *sc)
    535 {
    536     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_READ_ARRAY);
    537 }
    538 
    539 /* Read the status register
    540  */
    541 static uint8_t ReadStatusRegister(struct eflash_softc *sc)
    542 {
    543     uint8_t Status;
    544 
    545     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_READ_STATUS);
    546     sc->sc_ops->read_uint8(sc,sc->sc_page0,&Status);
    547     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_READ_ARRAY);
    548     return Status;
    549 }
    550 
    551 /* Clear error bits in status
    552  */
    553 static void ClearStatusRegister(struct eflash_softc *sc)
    554 {
    555     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_CLEAR_STATUS);
    556 }
    557 
    558 #if DEBUG
    559 /* Decode status bits
    560  */
    561 typedef const char *string;
    562 
    563 static void PrintStatus(uint8_t Status)
    564 {
    565     /* BUGBUG there's a %b format I think? */
    566     string BitNames[8] = {
    567         "reserved", "BLOCK_LOCKED",
    568         "PROGRAM_SUSPENDED", "LOW_VOLTAGE",
    569         "LOCK_BIT_ERROR", "ERASE_ERROR",
    570         "ERASE_SUSPENDED", "READY"
    571     };
    572     int i;
    573     int  OneSet = FALSE;
    574 
    575     printf("[status %x =",Status);
    576     for (i = 0; i < 8; i++) {
    577         if (Status & (1<<i)) {
    578             printf("%c%s",
    579                      (OneSet) ? '|' : ' ',
    580                      BitNames[i]);
    581             OneSet = TRUE;
    582         }
    583     }
    584     printf("]\n");
    585 }
    586 #else
    587 #define PrintStatus(x)
    588 #endif
    589 
    590 /*
    591  * The device can lock up under certain conditions.
    592  * There is no software workaround [must toggle RP# to GND]
    593  * Check if it seems that we are in that state.
    594  */
    595 static int  IsIrresponsive(struct eflash_softc *sc)
    596 {
    597     uint8_t Status = ReadStatusRegister(sc);
    598 
    599     if (Status & ST_READY)
    600         return FALSE;
    601 
    602     if ((Status & ST_MASK) ==
    603         (ST_LOCK_BIT_ERROR|ST_ERASE_SUSPENDED|ST_ERASE_ERROR)) {
    604         /* yes, looks that way */
    605         return TRUE;
    606     }
    607 
    608     /* Something is indeed amiss, but we dont really know for sure */
    609     PrintStatus(ReadStatusRegister(sc));
    610     ClearStatusRegister(sc);
    611     PrintStatus(ReadStatusRegister(sc));
    612 
    613     if ((Status & ST_MASK) ==
    614         (ST_LOCK_BIT_ERROR|ST_ERASE_SUSPENDED|ST_ERASE_ERROR)) {
    615         /* yes, looks that way */
    616         return TRUE;
    617     }
    618 
    619     return FALSE;
    620 }
    621 
    622 
    623 /* Write one 16bit word
    624  */
    625 static int
    626 single_program_word(struct eflash_softc *sc, volatile void *Offset, uint16_t *Values,
    627                   int  Verify, int *nWritten)
    628 {
    629     uint8_t Status;
    630     uint16_t i, Data16, Value;
    631 
    632     *nWritten = 0;
    633 
    634     Value = Values[0];
    635 
    636     if (Verify) {
    637         sc->sc_ops->read_uint16(sc,Offset,&Data16);
    638 #ifdef Verbose
    639         if (Verbose) {
    640             printf("Location %p was x%x\n",
    641                    Offset, Data16);
    642         }
    643 #endif
    644         if (Data16 != 0xffff)
    645             printf("Offset %p not ERASED, wont take.\n",Offset);
    646     }
    647 
    648     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_WRITE_WORD);
    649     sc->sc_ops->write_uint16(sc,Offset,Value);
    650 
    651     /* Wait until the operation is completed
    652      * Specs say it takes between 210 and 630 us
    653      * Errata says 360 TYP and Max=TBD (sic)
    654      */
    655     DELAY(800);
    656 
    657     for (i = 0; i < 10; i++) {
    658         sc->sc_ops->read_uint8(sc,Offset,&Status);
    659         if ((Status & ST_READY)) break;
    660         DELAY(100);
    661     }
    662 
    663     ProductIdExit(sc);
    664 
    665     if (Verify) {
    666         sc->sc_ops->read_uint16(sc,Offset,&Data16);
    667 #ifdef Verbose
    668         if (Verbose) {
    669             printf("Location %p is now x%x\n",
    670                    Offset, Data16);
    671         }
    672 #endif
    673         if ((Data16 != Value)) {
    674             PrintStatus(Status);
    675             printf(". That didnt work, try again.. [%x != %x]\n",
    676                    Data16, Value);
    677             ClearStatusRegister(sc);
    678             return FALSE;
    679         }
    680     }
    681 
    682     *nWritten = 2;
    683     return TRUE;
    684 }
    685 
    686 /* Write one buffer, 16bit words at a time
    687  */
    688 static int
    689 single_program_buffer(struct eflash_softc *sc, volatile void *Offset, uint16_t *Values,
    690                   int  Verify, int *nWritten)
    691 {
    692     uint8_t Status;
    693     uint16_t i, Data16, Value = 0;
    694     volatile uint8_t *Where = Offset;
    695 
    696     *nWritten = 0;
    697     if (sc->sc_buffersize == 0)
    698         return FALSE; /* sanity */
    699 
    700     if (Verify) {
    701         for (i = 0; i < sc->sc_buffersize; i+= 2) {
    702             sc->sc_ops->read_uint16(sc,Where+i,&Data16);
    703 #ifdef Verbose
    704             if (Verbose) {
    705                 printf("Location %p was x%x\n",
    706                        Where+i, Data16);
    707             }
    708 #endif
    709 
    710             if (Data16 != 0xffff)
    711                 printf("Offset %p not ERASED, wont take.\n",Where+i);
    712         }
    713     }
    714 
    715     /* Specs say to retry if necessary */
    716     for (i = 0; i < 5; i++) {
    717         sc->sc_ops->write_uint8(sc,Offset,CMD_WRITE_BUFFER);
    718         DELAY(10);
    719         sc->sc_ops->read_uint8(sc,Offset,&Status);
    720         if ((Status & ST_READY)) break;
    721     }
    722     if (0 == (Status & ST_READY)) {
    723         printf("FAILED program_buffer at Location %p, Status= x%x\n",
    724                  Offset, Status);
    725         return FALSE;
    726     }
    727 
    728     /* Say how many words we'll be sending */
    729     sc->sc_ops->write_uint8(sc,Offset,(uint8_t)(sc->sc_buffersize/2));
    730 
    731     /* Send the data */
    732     for (i = 0; i < sc->sc_buffersize; i+= 2) {
    733         Value = Values[i/2];
    734         sc->sc_ops->write_uint16(sc,Where+i,Value);
    735         DELAY(10);/*jic*/
    736     }
    737 
    738     /* Write confirmation */
    739     sc->sc_ops->write_uint8(sc,Offset,CMD_CONFIRM);
    740 
    741     /* Wait until the operation is completed
    742      * Specs say it takes between 800 and 2400 us
    743      * Errata says 1600 TYP and Max=TBD (sic), but fixed in stepping A3 and above.
    744      */
    745     DELAY(800);
    746 
    747     for (i = 0; i < 20; i++) {
    748         sc->sc_ops->write_uint8(sc,Offset,CMD_READ_STATUS);
    749         sc->sc_ops->read_uint8(sc,Offset,&Status);
    750         if ((Status & ST_READY)) break;
    751         DELAY(200);
    752     }
    753 
    754     ProductIdExit(sc);
    755 
    756     /* Verify? */
    757     if (Verify) {
    758         for (i = 0; i < sc->sc_buffersize; i+= 2) {
    759             sc->sc_ops->read_uint16(sc,Where+i,&Data16);
    760 #ifdef Verbose
    761             if (Verbose) {
    762                 printf("Location %p is now x%x\n",
    763                        Where+i, Data16);
    764             }
    765 #endif
    766             Value = Values[i/2];
    767 
    768             if ((Data16 != Value)) {
    769                 PrintStatus(Status);
    770                 printf(". That didnt work, try again.. [%x != %x]\n",
    771                        Data16, Value);
    772                 ClearStatusRegister(sc);
    773                 return FALSE;
    774             }
    775         }
    776     }
    777 
    778     *nWritten = sc->sc_buffersize;
    779     return TRUE;
    780 }
    781 
    782 /* Write one 32bit word
    783  */
    784 static int
    785 twin_program_word(struct eflash_softc *sc, volatile void *Offset, uint16_t *Values,
    786                 int  Verify, int *nWritten)
    787 {
    788     uint8_t Status;
    789     uint32_t i, Data32, Value;
    790     uint16_t v0, v1;
    791 
    792     *nWritten = 0;
    793 
    794     v0 = Values[0];
    795     v0 = le16toh(v0);
    796     v1 = Values[1];
    797     v1 = le16toh(v1);
    798     Value = v0 | ((uint32_t)v1 << 16);
    799     if (Verify) {
    800         sc->sc_ops->read_uint32(sc,Offset,&Data32);
    801 #ifdef Verbose
    802         if (Verbose) {
    803             printf("Location %p was x%x\n",
    804                    Offset, Data32);
    805         }
    806 #endif
    807         if (Data32 != 0xffffffff)
    808             printf("Offset %p not ERASED, wont take.\n",Offset);
    809     }
    810 
    811     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_WRITE_WORD);
    812     sc->sc_ops->write_uint32(sc,Offset,Value);
    813 
    814     /* Wait until the operation is completed
    815      * Specs say it takes between 210 and 630 us
    816      * Errata says 360 TYP and Max=TBD (sic)
    817      */
    818     DELAY(400);
    819 
    820     for (i = 0; i < 10; i++) {
    821         sc->sc_ops->read_uint8(sc,Offset,&Status);
    822         if ((Status & ST_READY)) break;
    823         DELAY(100);
    824     }
    825 
    826     ProductIdExit(sc);
    827 
    828     if (Verify) {
    829         sc->sc_ops->read_uint32(sc,Offset,&Data32);
    830 #ifdef Verbose
    831         if (Verbose) {
    832             printf("Location %p is now x%x\n",
    833                    Offset, Data32);
    834         }
    835 #endif
    836         if ((Data32 != Value)) {
    837             PrintStatus(Status);
    838             printf(". That didnt work, try again.. [%x != %x]\n",
    839                    Data32, Value);
    840             ClearStatusRegister(sc);
    841             return FALSE;
    842         }
    843     }
    844 
    845     *nWritten = 4;
    846     return TRUE;
    847 }
    848 
    849 /* Write one buffer, 32bit words at a time
    850  */
    851 static int
    852 twin_program_buffer(struct eflash_softc *sc, volatile void *Offset, uint16_t *Values,
    853                 int  Verify, int *nWritten)
    854 {
    855     uint8_t Status;
    856     uint32_t i, Data32, Value;
    857     uint16_t v0 = 0, v1;
    858     volatile uint8_t *Where = Offset;
    859 
    860     *nWritten = 0;
    861     if (sc->sc_buffersize == 0)
    862         return FALSE; /* sanity */
    863 
    864     if (Verify) {
    865         for (i = 0; i < sc->sc_buffersize; i+= 4) {
    866             sc->sc_ops->read_uint32(sc,Where+i,&Data32);
    867 #ifdef Verbose
    868             if (Verbose) {
    869                 printf("Location %p was x%x\n",
    870                        Where+i, Data32);
    871             }
    872 #endif
    873             if (Data32 != 0xffffffff)
    874                 printf("Offset %p not ERASED, wont take.\n",Where+i);
    875         }
    876     }
    877 
    878     /* Specs say to retry if necessary */
    879     for (i = 0; i < 5; i++) {
    880         sc->sc_ops->write_uint8(sc,Offset,CMD_WRITE_BUFFER);
    881         DELAY(10);
    882         sc->sc_ops->read_uint8(sc,Offset,&Status);
    883         if ((Status & ST_READY)) break;
    884     }
    885     if (0 == (Status & ST_READY)) {
    886         printf("FAILED program_buffer at Location %p, Status= x%x\n",
    887                  Offset, Status);
    888         return FALSE;
    889     }
    890 
    891     /* Say how many words we'll be sending */
    892     sc->sc_ops->write_uint8(sc,Offset,(uint8_t)(sc->sc_buffersize/4)); /* to each twin! */
    893 
    894     /* Send the data */
    895     for (i = 0; i < sc->sc_buffersize; i+= 4) {
    896         v0 = Values[i/2];
    897         v0 = le16toh(v0);
    898         v1 = Values[1+(i/2)];
    899         v1 = le16toh(v1);
    900         Value = v0 | ((uint32_t)v1 << 16);
    901         sc->sc_ops->write_uint32(sc,Where+i,Value);
    902         DELAY(10);/*jic*/
    903     }
    904 
    905     /* Write confirmation */
    906     sc->sc_ops->write_uint8(sc,Offset,CMD_CONFIRM);
    907 
    908     /* Wait until the operation is completed
    909      * Specs say it takes between 800 and 2400 us
    910      * Errata says 1600 TYP and Max=TBD (sic), but fixed in stepping A3 and above.
    911      */
    912     DELAY(800);
    913 
    914     for (i = 0; i < 20; i++) {
    915         sc->sc_ops->write_uint8(sc,Offset,CMD_READ_STATUS);
    916         sc->sc_ops->read_uint8(sc,Offset,&Status);
    917         if ((Status & ST_READY)) break;
    918         DELAY(200);
    919     }
    920 
    921     ProductIdExit(sc);
    922 
    923     /* Verify */
    924     if (Verify) {
    925         for (i = 0; i < sc->sc_buffersize; i+= 4) {
    926             sc->sc_ops->read_uint32(sc,Where+i,&Data32);
    927 #ifdef Verbose
    928             if (Verbose) {
    929                 printf("Location %p is now x%x\n",
    930                        Where+i, Data32);
    931             }
    932 #endif
    933             v0 = Values[i/2];
    934             v0 = le16toh(v0);
    935             v1 = Values[1+(i/2)];
    936             v1 = le16toh(v1);
    937             Value = v0 | ((uint32_t)v1 << 16);
    938 
    939             if ((Data32 != Value)) {
    940                 PrintStatus(Status);
    941                 printf(". That didnt work, try again.. [%x != %x]\n",
    942                        Data32, Value);
    943                 ClearStatusRegister(sc);
    944                 return FALSE;
    945             }
    946         }
    947     }
    948 
    949     *nWritten = sc->sc_buffersize;
    950     return TRUE;
    951 }
    952 
    953 /* Is there a lock on a given sector
    954  */
    955 static int IsSectorLocked(struct eflash_softc *sc, uint8_t *secptr)
    956 {
    957     uint8_t Data, Data1;
    958 
    959     ProductIdEnter(sc);
    960     /* Lockout info is at address 2 of the given sector, meaning A0=0 A1=1.
    961      */
    962     sc->sc_ops->read_uint8(sc,secptr+(0x0002*2*sc->sc_chips),&Data);
    963     sc->sc_ops->read_uint8(sc,secptr+(0x0003*2*sc->sc_chips),&Data1);
    964 
    965     ProductIdExit(sc);
    966 
    967     return (Data & 1);
    968 }
    969 
    970 /* Remove the write-lock to a sector
    971  */
    972 static void SectorUnLock(struct eflash_softc *sc, uint8_t *secptr)
    973 {
    974     uint8_t Status;
    975     int i;
    976 
    977     DBGME(DEBUG_FUNCS,printf("%s: Unlocking sector %d [ptr %p] ...\n",
    978 	device_xname(sc->sc_dev), sc->sc_sector_offset, secptr));
    979 
    980     sc->sc_ops->write_uint8(sc,sc->sc_page0,CMD_SET_PREFIX);
    981     sc->sc_ops->write_uint8(sc,secptr,CMD_UNLOCK);
    982 
    983     /* Wait until the unlock is complete.
    984      * Specs say this takes between 64 and 75 usecs.
    985      */
    986     DELAY(100);
    987 
    988     for (i = 0; i < 10; i++) {
    989         sc->sc_ops->read_uint8(sc,secptr,&Status);
    990         if ((Status & ST_READY)) break;
    991         DELAY(100);
    992     }
    993 
    994     ProductIdExit(sc);
    995 
    996     if ((Status & ST_MASK) == ST_READY) {
    997         DBGME(DEBUG_FUNCS,printf("%s: Unlocked ok.\n",
    998 	    device_xname(sc->sc_dev)));
    999         return;
   1000     }
   1001 
   1002     PrintStatus(Status);
   1003     DBGME(DEBUG_ERRORS,printf("%s: Unlock of sector %d NOT completed (status=%x).\n",
   1004                               device_xname(sc->sc_dev),
   1005 			      sc->sc_sector_offset, Status));
   1006     ClearStatusRegister(sc);
   1007 }
   1008 
   1009 
   1010 /* Erase one sector
   1011  */
   1012 static int  SectorErase(struct eflash_softc *sc, void *secptr)
   1013 {
   1014     uint8_t Status = 0;
   1015     uint16_t i;
   1016 
   1017     DBGME(DEBUG_FUNCS,printf("%s: Erasing sector %d [ptr %p] ...\n",
   1018 	device_xname(sc->sc_dev), sc->sc_sector_offset, secptr));
   1019 
   1020     /* On some chips we just cannot avoid the locking business.
   1021      */
   1022     if ((sc->sc_chips == 1) &&
   1023         IsSectorLocked(sc,secptr))
   1024         SectorUnLock(sc,secptr);
   1025 
   1026     sc->sc_ops->write_uint8(sc,secptr,CMD_ERASE_SETUP);
   1027     sc->sc_ops->write_uint8(sc,secptr,CMD_ERASE_CONFIRM);
   1028 
   1029     /* Wait until the erase is actually completed
   1030      * Specs say it will take between 1 and 5 seconds.
   1031      * Errata says it takes 2 sec min and 25 sec max.
   1032      * Double that before giving up.
   1033      */
   1034     for (i = 0; i < 20; i++) {
   1035         /* Sleep for at least 2 seconds
   1036          */
   1037         tsleep(sc,PWAIT,"erase", hz * 2);
   1038 
   1039         sc->sc_ops->read_uint8(sc,secptr,&Status);
   1040         if ((Status & ST_READY)) break;
   1041         PrintStatus(Status);
   1042     }
   1043 
   1044     ProductIdExit(sc);
   1045 
   1046     if ((Status & ST_ERASE_MASK) == ST_READY) {
   1047         DBGME(DEBUG_FUNCS,printf("%s: Erased ok.\n", device_xname(sc->sc_dev)));
   1048         return 0;
   1049     }
   1050 
   1051     PrintStatus(Status);
   1052     DBGME(DEBUG_ERRORS,printf("%s: Erase of sector %d NOT completed (status=%x).\n",
   1053                               device_xname(sc->sc_dev),
   1054 			      sc->sc_sector_offset, Status));
   1055 
   1056     ClearStatusRegister(sc);
   1057     return EIO;
   1058 }
   1059 
   1060 
   1061 
   1062 /* Write (a portion of) a sector
   1063  */
   1064 static size_t eflash_write_sector(struct eflash_softc *sc, char *Buffer, size_t n,
   1065                                uint8_t *Offset, int Verify)
   1066 {
   1067     size_t i;
   1068 
   1069     /* Make sure the device is not screwed up
   1070      */
   1071     if (IsIrresponsive(sc)) {
   1072         printf("FLASH is locked-up (or mapped cacheable?), wont work. ");
   1073     }
   1074 
   1075     for (i = 0; i < n;) {
   1076         int nTries;
   1077         int nWritten = 0;/*we expect 2 or 4 */
   1078 
   1079         if (sc->sc_buffersize && ((n-i) >= sc->sc_buffersize)) {
   1080             for (nTries = 0; nTries < 5; nTries++)
   1081                 if (sc->sc_ops->program_buffer(sc,Offset,(uint16_t*)(Buffer+i),Verify,&nWritten))
   1082                     break;
   1083         } else {
   1084             for (nTries = 0; nTries < 5; nTries++)
   1085                 if (sc->sc_ops->program_word(sc,Offset,(uint16_t*)(Buffer+i),Verify,&nWritten))
   1086                     break;
   1087         }
   1088         Offset += nWritten;
   1089         i += nWritten;
   1090         if (nWritten == 0)
   1091             break;
   1092     }
   1093     return i;
   1094 }
   1095 
   1096 /* Identify type and the sector map of the FLASH.
   1097  * Argument is the base address of the device and the count of chips on the bus (1/2)
   1098  * Returns FALSE if failed
   1099  */
   1100 static const struct flash_ops single_ops = {
   1101     single_write_uint8,
   1102     single_read_uint8,
   1103     single_write_uint16,
   1104     single_read_uint16,
   1105     single_write_uint32,
   1106     single_read_uint32,
   1107     single_program_word,
   1108     single_program_buffer
   1109 };
   1110 
   1111 static const struct flash_ops twin_ops = {
   1112     twin_write_uint8,
   1113     twin_read_uint8,
   1114     twin_write_uint16,
   1115     twin_read_uint16,
   1116     twin_write_uint32,
   1117     twin_read_uint32,
   1118     twin_program_word,
   1119     twin_program_buffer
   1120 };
   1121 
   1122 static int  flash_identify(struct eflash_softc *sc)
   1123 {
   1124     uint8_t Mid, Did;
   1125     int i;
   1126 
   1127     if (sc->sc_chips > 1)
   1128         sc->sc_ops = &twin_ops;
   1129     else
   1130         sc->sc_ops = &single_ops;
   1131 
   1132     sc->sc_buffersize = 0;
   1133 #if USE_BUFFERED_WRITES
   1134     sc->sc_buffersize = BUFFER_BYTES * sc->sc_chips;
   1135 #endif
   1136     sc->sc_sector = NULL;
   1137     sc->sc_sector_size = 0;
   1138     sc->sc_sector_offset = NOSECTOR;
   1139     sc->sc_erased = FALSE;
   1140 
   1141     ProductIdEnter(sc);
   1142     sc->sc_ops->read_uint8(sc,sc->sc_page0+(0x0000*2*sc->sc_chips),&Mid);
   1143     sc->sc_ops->read_uint8(sc,sc->sc_page0+(0x0001*2*sc->sc_chips),&Did);
   1144     ProductIdExit(sc);
   1145 
   1146     sc->sc_type.ft_manuf_code = Mid;
   1147     sc->sc_type.ft_device_code = Did;
   1148 
   1149     for (i = 0; i < nMAPS; i++) {
   1150         if ((sector_maps[i].ft_manuf_code == Mid) && (sector_maps[i].ft_device_code == Did)) {
   1151             int j;
   1152             uint32_t ms = 0;
   1153             sc->sc_type = sector_maps[i];
   1154             /* double the sector sizes if twin-chips */
   1155             for (j = 0; j < nDELTAS; j++) {
   1156                 sc->sc_type.ft_deltas[j].nKB *= sc->sc_chips;
   1157                 if (ms < sc->sc_type.ft_deltas[j].nKB)
   1158                     ms = sc->sc_type.ft_deltas[j].nKB;
   1159             }
   1160             sc->sc_max_secsize = ms * 1024;
   1161             return TRUE;
   1162         }
   1163     }
   1164 
   1165     return FALSE;
   1166 }
   1167 
   1168 /* Common code for read&write argument validation
   1169  */
   1170 static int eflash_validate(struct eflash_softc *sc, daddr_t start, size_t *pSize, void **pSrc)
   1171 {
   1172     daddr_t Size;
   1173     uint32_t sec;
   1174     size_t secsize, secstart;
   1175 
   1176     /* Validate args
   1177      */
   1178     if (start >= sc->sc_capacity) {
   1179         *pSize = 0;
   1180         DBGME(DEBUG_ERRORS,printf("eflash::ValidateArg(%qx) EOF\n", start));
   1181         return E2BIG;
   1182     }
   1183 
   1184     /* Map sector if not already
   1185      */
   1186     sec = SectorNumber(&sc->sc_type, start << DEV_BSHIFT);
   1187     secsize = SectorSize( &sc->sc_type, sec);
   1188     secstart = SectorStart(&sc->sc_type,sec);
   1189     if (sec != sc->sc_sector_offset) {
   1190         int error;
   1191 
   1192         /* unmap previous first */
   1193         if (sc->sc_sector_offset != NOSECTOR) {
   1194             DBGME(DEBUG_FUNCS,printf("%s: unmap %p %zx\n",
   1195 		device_xname(sc->sc_dev), sc->sc_sector, sc->sc_sector_size));
   1196             iounaccess((vaddr_t)sc->sc_sector, sc->sc_sector_size);
   1197             sc->sc_sector_offset = NOSECTOR;
   1198         }
   1199 
   1200         /* map new */
   1201         error = ioaccess((vaddr_t)sc->sc_sector,
   1202                          secstart + sc->sc_base,
   1203                          secsize);
   1204         DBGME(DEBUG_FUNCS,printf("%s: mapped %p %zx -> %zx %d\n",
   1205 	    device_xname(sc->sc_dev),
   1206 	    sc->sc_sector, secsize, secstart + sc->sc_base,error));
   1207         if (error) return error;
   1208 
   1209         /* Update state. We have to assume the sector was not erased. Sigh. */
   1210         sc->sc_sector_offset = sec;
   1211         sc->sc_sector_size = secsize;
   1212         sc->sc_erased = FALSE;
   1213     }
   1214 
   1215     /* Adjust size if necessary
   1216      */
   1217     Size = start + *pSize; /* last sector */
   1218     if (Size > sc->sc_capacity) {
   1219         /* At most this many sectors
   1220          */
   1221         Size = sc->sc_capacity - start;
   1222         *pSize = (size_t)Size;
   1223     }
   1224     if (*pSize > (secsize >> DEV_BSHIFT)) {
   1225         *pSize = secsize >> DEV_BSHIFT;
   1226     }
   1227 
   1228     *pSrc = sc->sc_sector + (start << DEV_BSHIFT) - secstart;
   1229 
   1230     DBGME(DEBUG_FUNCS,printf("%s: Validate %qx %zd %p\n",
   1231 	device_xname(sc->sc_dev), start,*pSize, *pSrc));
   1232     return 0;
   1233 }
   1234 
   1235 static int eflash_read_at (struct eflash_softc *sc,
   1236                            daddr_t start_sector, char *buffer, size_t nblocks,
   1237                            size_t * pSizeRead)
   1238 {
   1239     int error;
   1240     uint32_t SizeRead = 0;
   1241     void *src;
   1242 
   1243     DBGME(DEBUG_XFERS|DEBUG_READS,printf("%s: EflashReadAt(%qx %p %zd %p)\n",
   1244                      device_xname(sc->sc_dev), start_sector, buffer, nblocks, pSizeRead));
   1245 
   1246     /* Validate & trim arguments
   1247      */
   1248     error = eflash_validate(sc, start_sector, &nblocks, &src);
   1249 
   1250     /* Copy data if
   1251      */
   1252     if (error == 0) {
   1253         SizeRead = nblocks;
   1254         memcpy(buffer, src, nblocks << DEV_BSHIFT);
   1255     }
   1256 
   1257     if (pSizeRead)
   1258         *pSizeRead = SizeRead;
   1259     return error;
   1260 }
   1261 
   1262 /* Write SIZE bytes to device.
   1263  */
   1264 static int eflash_write_at (struct eflash_softc *sc,
   1265                            daddr_t start_sector, char *buffer, size_t nblocks,
   1266                            size_t * pSizeWritten)
   1267 {
   1268     int error;
   1269     void *src;
   1270     size_t SizeWritten = 0;
   1271 
   1272     DBGME(DEBUG_XFERS|DEBUG_WRITES,printf("%s: EflashWriteAt(%qx %p %zd %p)\n",
   1273                      device_xname(sc->sc_dev), start_sector, buffer, nblocks, pSizeWritten));
   1274 
   1275     /* Validate & trim arguments
   1276      */
   1277     error = eflash_validate(sc, start_sector, &nblocks, &src);
   1278 
   1279     if (error == 0) {
   1280         /* Do we have to erase it */
   1281         if (! sc->sc_erased) {
   1282 
   1283             error = SectorErase(sc,src);
   1284             if (error)
   1285                 goto Out;
   1286             sc->sc_erased = TRUE;
   1287         }
   1288         SizeWritten = eflash_write_sector(sc, buffer, nblocks << DEV_BSHIFT, src, TRUE);
   1289         SizeWritten >>= DEV_BSHIFT;
   1290     }
   1291 
   1292  Out:
   1293     if (pSizeWritten)
   1294         *pSizeWritten = SizeWritten;
   1295     return error;
   1296 }
   1297 
   1298 /* Rest of code lifted with mods from the dev\ata\wd.c driver
   1299  */
   1300 
   1301 /*
   1302  * Copyright (c) 1998, 2001 Manuel Bouyer.  All rights reserved.
   1303  *
   1304  * Redistribution and use in source and binary forms, with or without
   1305  * modification, are permitted provided that the following conditions
   1306  * are met:
   1307  * 1. Redistributions of source code must retain the above copyright
   1308  *	notice, this list of conditions and the following disclaimer.
   1309  * 2. Redistributions in binary form must reproduce the above copyright
   1310  *	notice, this list of conditions and the following disclaimer in the
   1311  *	documentation and/or other materials provided with the distribution.
   1312  *
   1313  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   1314  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   1315  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   1316  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   1317  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   1318  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   1319  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   1320  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   1321  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   1322  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   1323  */
   1324 
   1325 /*-
   1326  * Copyright (c) 1998, 2003, 2004 The NetBSD Foundation, Inc.
   1327  * All rights reserved.
   1328  *
   1329  * This code is derived from software contributed to The NetBSD Foundation
   1330  * by Charles M. Hannum and by Onno van der Linden.
   1331  *
   1332  * Redistribution and use in source and binary forms, with or without
   1333  * modification, are permitted provided that the following conditions
   1334  * are met:
   1335  * 1. Redistributions of source code must retain the above copyright
   1336  *    notice, this list of conditions and the following disclaimer.
   1337  * 2. Redistributions in binary form must reproduce the above copyright
   1338  *    notice, this list of conditions and the following disclaimer in the
   1339  *    documentation and/or other materials provided with the distribution.
   1340  *
   1341  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   1342  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   1343  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   1344  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   1345  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   1346  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   1347  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   1348  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   1349  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   1350  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   1351  * POSSIBILITY OF SUCH DAMAGE.
   1352  */
   1353 
   1354 static const char ST506[] = "ST506";
   1355 
   1356 #define	EFLASHIORETRIES_SINGLE 4	/* number of retries before single-sector */
   1357 #define	EFLASHIORETRIES	5	/* number of retries before giving up */
   1358 #define	RECOVERYTIME hz/2	/* time to wait before retrying a cmd */
   1359 
   1360 #define	EFLASHUNIT(dev)		DISKUNIT(dev)
   1361 #define	EFLASHPART(dev)		DISKPART(dev)
   1362 #define	EFLASHMINOR(unit, part)	DISKMINOR(unit, part)
   1363 #define	MAKEEFLASHDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)
   1364 
   1365 #define	EFLASHLABELDEV(dev)	(MAKEEFLASHDEV(major(dev), EFLASHUNIT(dev), RAW_PART))
   1366 
   1367 void	eflashperror(const struct eflash_softc *);
   1368 
   1369 extern struct cfdriver eflash_cd;
   1370 
   1371 dev_type_open(eflashopen);
   1372 dev_type_close(eflashclose);
   1373 dev_type_read(eflashread);
   1374 dev_type_write(eflashwrite);
   1375 dev_type_ioctl(eflashioctl);
   1376 dev_type_strategy(eflashstrategy);
   1377 dev_type_dump(eflashdump);
   1378 dev_type_size(eflashsize);
   1379 
   1380 const struct bdevsw eflash_bdevsw = {
   1381 	.d_open = eflashopen,
   1382 	.d_close = eflashclose,
   1383 	.d_strategy = eflashstrategy,
   1384 	.d_ioctl = eflashioctl,
   1385 	.d_dump = eflashdump,
   1386 	.d_psize = eflashsize,
   1387 	.d_discard = nodiscard,
   1388 	.d_flag = D_DISK
   1389 };
   1390 
   1391 const struct cdevsw eflash_cdevsw = {
   1392 	.d_open = eflashopen,
   1393 	.d_close = eflashclose,
   1394 	.d_read = eflashread,
   1395 	.d_write = eflashwrite,
   1396 	.d_ioctl = eflashioctl,
   1397 	.d_stop = nostop,
   1398 	.d_tty = notty,
   1399 	.d_poll = nopoll,
   1400 	.d_mmap = nommap,
   1401 	.d_kqfilter = nokqfilter,
   1402 	.d_discard = nodiscard,
   1403 	.d_flag = D_DISK
   1404 };
   1405 
   1406 void  eflashgetdefaultlabel(struct eflash_softc *, struct disklabel *);
   1407 void  eflashgetdisklabel(struct eflash_softc *);
   1408 void  eflashstart(void *);
   1409 void  __eflashstart(struct eflash_softc *, struct buf *);
   1410 void  eflashrestart(void *);
   1411 void  eflashattach(struct eflash_softc *);
   1412 int   eflashdetach(device_t, int);
   1413 int   eflashactivate(device_t, enum devact);
   1414 
   1415 void  eflashdone(struct eflash_softc *);
   1416 static void eflash_set_geometry(struct eflash_softc *sc);
   1417 
   1418 struct dkdriver eflashdkdriver = {
   1419 	.d_strategy = eflashstrategy,
   1420 	.d_minphys = minphys
   1421 };
   1422 
   1423 static void eflash_wedges(void *arg);
   1424 
   1425 void
   1426 eflashattach(struct eflash_softc *sc)
   1427 {
   1428 	device_t self = sc->sc_dev;
   1429 	char pbuf[9];
   1430 	DEBUG_PRINT(("%s: eflashattach\n",  device_xname(sc->sc_dev)), DEBUG_FUNCS | DEBUG_PROBE);
   1431 
   1432 	callout_init(&sc->sc_restart_ch, 0);
   1433 	bufq_alloc(&sc->sc_q, BUFQ_DISK_DEFAULT_STRAT, BUFQ_SORT_RAWBLOCK);
   1434 
   1435     sc->openings = 1; /* wazziz?*/
   1436 
   1437 	aprint_naive("\n");
   1438 
   1439     /* setup all required fields so that if the attach fails we are ok */
   1440 	sc->sc_dk.dk_driver = &eflashdkdriver;
   1441 	sc->sc_dk.dk_name = device_xname(sc->sc_dev);
   1442 
   1443 	format_bytes(pbuf, sizeof(pbuf), sc->sc_capacity * DEV_BSIZE);
   1444 	aprint_normal("%s: %s, %d cyl, %d head, %d sec, %d bytes/sect x %llu sectors\n",
   1445 	    device_xname(self), pbuf, 1, 1, sc->sc_capacity,
   1446 	    DEV_BSIZE, (unsigned long long)sc->sc_capacity);
   1447 
   1448     eflash_set_geometry(sc);
   1449 
   1450 	/*
   1451 	 * Attach the disk structure. We fill in dk_info later.
   1452 	 */
   1453 	disk_attach(&sc->sc_dk);
   1454 
   1455 	rnd_attach_source(&sc->rnd_source, device_xname(sc->sc_dev),
   1456 			  RND_TYPE_DISK, RND_FLAG_DEFAULT);
   1457 
   1458 }
   1459 
   1460 int
   1461 eflashactivate(device_t self, enum devact act)
   1462 {
   1463 	int rv = 0;
   1464 
   1465 	DEBUG_PRINT(("eflashactivate %x\n",  act), DEBUG_FUNCS | DEBUG_PROBE);
   1466 
   1467 	switch (act) {
   1468 	case DVACT_DEACTIVATE:
   1469 		/*
   1470 		 * Nothing to do; we key off the device's DVF_ACTIVATE.
   1471 		 */
   1472 		break;
   1473 	default:
   1474 		rv = EOPNOTSUPP;
   1475 		break;
   1476 	}
   1477 	return (rv);
   1478 }
   1479 
   1480 int
   1481 eflashdetach(device_t self, int flags)
   1482 {
   1483 	struct eflash_softc *sc = device_private(self);
   1484 	int s, bmaj, cmaj, i, mn;
   1485 
   1486 	DEBUG_PRINT(("%s: eflashdetach\n",  device_xname(sc->sc_dev)), DEBUG_FUNCS | DEBUG_PROBE);
   1487 
   1488 	/* locate the major number */
   1489 	bmaj = bdevsw_lookup_major(&eflash_bdevsw);
   1490 	cmaj = cdevsw_lookup_major(&eflash_cdevsw);
   1491 
   1492 	/* Nuke the vnodes for any open instances. */
   1493 	for (i = 0; i < MAXPARTITIONS; i++) {
   1494 		mn = EFLASHMINOR(device_unit(self), i);
   1495 		vdevgone(bmaj, mn, mn, VBLK);
   1496 		vdevgone(cmaj, mn, mn, VCHR);
   1497 	}
   1498 
   1499 	/* Delete all of our wedges. */
   1500 	dkwedge_delall(&sc->sc_dk);
   1501 
   1502 	s = splbio();
   1503 
   1504 	/* Kill off any queued buffers. */
   1505 	bufq_drain(sc->sc_q);
   1506 
   1507 	/*sc->atabus->ata_killpending(sc->drvp);*/
   1508 
   1509 	splx(s);
   1510 	bufq_free(sc->sc_q);
   1511 
   1512 	/* Detach disk. */
   1513 	disk_detach(&sc->sc_dk);
   1514 
   1515 	/* Unhook the entropy source. */
   1516 	rnd_detach_source(&sc->rnd_source);
   1517 
   1518 	/*sc->drvp->drive_flags = 0; -- no drive any more here */
   1519 
   1520 	return (0);
   1521 }
   1522 
   1523 extern int	dkwedge_autodiscover;
   1524 
   1525 /* Aux temp thread to avoid deadlock when doing the partitio.. ahem wedges thing.
   1526  */
   1527 static void
   1528 eflash_wedges(void *arg)
   1529 {
   1530 	struct eflash_softc *sc = (struct eflash_softc*)arg;
   1531 
   1532     DBGME(DEBUG_STATUS,printf("%s: wedges started for %p\n", sc->sc_dk.dk_name, sc));
   1533 
   1534 	/* Discover wedges on this disk. */
   1535     dkwedge_autodiscover = 1;
   1536 	dkwedge_discover(&sc->sc_dk);
   1537 
   1538     config_pending_decr(sc->sc_dev);
   1539 
   1540     DBGME(DEBUG_STATUS,printf("%s: wedges thread done for %p\n", device_xname(sc->sc_dev), sc));
   1541 	kthread_exit(0);
   1542 }
   1543 
   1544 static void
   1545 eflash_thread(void *arg)
   1546 {
   1547 	struct eflash_softc *sc = (struct eflash_softc*)arg;
   1548 	struct buf *bp;
   1549     vaddr_t addr;
   1550 	int s, error;
   1551 
   1552     DBGME(DEBUG_STATUS,printf("%s: thread started for %p\n", device_xname(sc->sc_dev), sc));
   1553 
   1554     s = splbio();
   1555     eflashattach(sc);
   1556     splx(s);
   1557 
   1558     /* Allocate a VM window large enough to map the largest sector
   1559      * BUGBUG We could risk it and allocate/free on open/close?
   1560      */
   1561     addr = uvm_km_alloc(kernel_map, sc->sc_max_secsize, 0, UVM_KMF_VAONLY);
   1562     if (addr == 0)
   1563         panic("eflash_thread: kernel map full (%lx)", (long unsigned)sc->sc_max_secsize);
   1564     sc->sc_sector = (/*volatile*/ uint8_t *) addr;
   1565     sc->sc_sector_size = 0;
   1566     sc->sc_sector_offset = NOSECTOR;
   1567 
   1568 	error = kthread_create(PRI_NONE, 0, NULL,
   1569 	    eflash_wedges, sc, NULL, "%s.wedges", device_xname(sc->sc_dev));
   1570 	if (error) {
   1571 		aprint_error_dev(sc->sc_dev, "wedges: unable to create kernel "
   1572 		    "thread: error %d\n", error);
   1573 		/* XXX: why continue? */
   1574 	}
   1575 
   1576 
   1577     DBGME(DEBUG_STATUS,printf("%s: thread service active for %p\n", device_xname(sc->sc_dev), sc));
   1578 
   1579     s = splbio();
   1580 	for (;;) {
   1581         /* Get next I/O request, wait if necessary
   1582          */
   1583 		if ((sc->ch_flags & (ATACH_TH_RESET | ATACH_SHUTDOWN)) == 0 &&
   1584 		    (sc->active_xfer == NULL)) {
   1585 			sc->ch_flags &= ~ATACH_TH_RUN;
   1586 			(void) tsleep(&sc->ch_thread, PRIBIO, "eflashth", 0);
   1587 			sc->ch_flags |= ATACH_TH_RUN;
   1588 		}
   1589 		if (sc->ch_flags & ATACH_SHUTDOWN) {
   1590 			break;
   1591         }
   1592         bp = sc->active_xfer;
   1593         sc->active_xfer = NULL;
   1594 		if (bp != NULL) {
   1595 
   1596             size_t sz = DEV_BSIZE, bnow;
   1597 
   1598             DBGME(DEBUG_XFERS,printf("%s: task %p %x %p %qx %d (%zd)\n", device_xname(sc->sc_dev), bp,
   1599                                      sc->sc_bio.flags, sc->sc_bio.databuf, sc->sc_bio.blkno,
   1600                                      sc->sc_bio.nbytes, sc->sc_bio.nblks));
   1601 
   1602             sc->sc_bio.error = 0;
   1603             for (; sc->sc_bio.nblks > 0;) {
   1604 
   1605                 bnow = sc->sc_bio.nblks;
   1606                 if (sc->sc_bio.flags & ATA_SINGLE) bnow = 1;
   1607 
   1608                 if (sc->sc_bio.flags & ATA_READ) {
   1609                     sc->sc_bio.error =
   1610                         eflash_read_at(sc, sc->sc_bio.blkno, sc->sc_bio.databuf, bnow, &sz);
   1611                 } else {
   1612                     sc->sc_bio.error =
   1613                         eflash_write_at(sc, sc->sc_bio.blkno, sc->sc_bio.databuf, bnow, &sz);
   1614                 }
   1615 
   1616                 if (sc->sc_bio.error)
   1617                     break;
   1618 
   1619                 sc->sc_bio.blkno += sz; /* in blocks */
   1620                 sc->sc_bio.nblks -= sz;
   1621                 sc->sc_bio.blkdone += sz;
   1622                 sz = sz << DEV_BSHIFT; /* in bytes */
   1623                 sc->sc_bio.databuf += sz;
   1624                 sc->sc_bio.nbytes  -= sz;
   1625             }
   1626 
   1627             eflashdone(sc);
   1628         }
   1629 	}
   1630 
   1631 	splx(s);
   1632 	sc->ch_thread = NULL;
   1633 	wakeup(&sc->ch_flags);
   1634 
   1635     DBGME(DEBUG_STATUS,printf("%s: thread service terminated for %p\n", device_xname(sc->sc_dev), sc));
   1636 
   1637 	kthread_exit(0);
   1638 }
   1639 
   1640 
   1641 /*
   1642  * Read/write routine for a buffer.  Validates the arguments and schedules the
   1643  * transfer.  Does not wait for the transfer to complete.
   1644  */
   1645 void
   1646 eflashstrategy(struct buf *bp)
   1647 {
   1648 	struct eflash_softc *sc = device_lookup_private(&eflash_cd, EFLASHUNIT(bp->b_dev));
   1649 	struct disklabel *lp = sc->sc_dk.dk_label;
   1650 	daddr_t blkno;
   1651 	int s;
   1652 
   1653 	DEBUG_PRINT(("%s: eflashstrategy %lld\n", device_xname(sc->sc_dev), bp->b_blkno),
   1654 	    DEBUG_XFERS);
   1655 
   1656 	/* Valid request?  */
   1657 	if (bp->b_blkno < 0 ||
   1658 	    (bp->b_bcount % lp->d_secsize) != 0 ||
   1659 	    (bp->b_bcount / lp->d_secsize) >= (1 << NBBY)) {
   1660 		bp->b_error = EINVAL;
   1661 		goto done;
   1662 	}
   1663 
   1664 	/* If device invalidated (e.g. media change, door open), error. */
   1665 	if ((sc->sc_flags & EFLASHF_LOADED) == 0) {
   1666 		bp->b_error = EIO;
   1667 		goto done;
   1668 	}
   1669 
   1670 	/* If it's a null transfer, return immediately. */
   1671 	if (bp->b_bcount == 0)
   1672 		goto done;
   1673 
   1674 	/*
   1675 	 * Do bounds checking, adjust transfer. if error, process.
   1676 	 * If end of partition, just return.
   1677 	 */
   1678 	if (EFLASHPART(bp->b_dev) == RAW_PART) {
   1679 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
   1680 		    sc->sc_capacity) <= 0)
   1681 			goto done;
   1682 	} else {
   1683 		if (bounds_check_with_label(&sc->sc_dk, bp,
   1684 		    (sc->sc_flags & (EFLASHF_WLABEL|EFLASHF_LABELLING)) != 0) <= 0)
   1685 			goto done;
   1686 	}
   1687 
   1688 	/*
   1689 	 * Now convert the block number to absolute and put it in
   1690 	 * terms of the device's logical block size.
   1691 	 */
   1692 	if (lp->d_secsize >= DEV_BSIZE)
   1693 		blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
   1694 	else
   1695 		blkno = bp->b_blkno * (DEV_BSIZE / lp->d_secsize);
   1696 
   1697 	if (EFLASHPART(bp->b_dev) != RAW_PART)
   1698 		blkno += lp->d_partitions[EFLASHPART(bp->b_dev)].p_offset;
   1699 
   1700 	bp->b_rawblkno = blkno;
   1701 
   1702 	/* Queue transfer on drive, activate drive and controller if idle. */
   1703 	s = splbio();
   1704 	bufq_put(sc->sc_q, bp);
   1705 	eflashstart(sc);
   1706 	splx(s);
   1707 	return;
   1708 done:
   1709 	/* Toss transfer; we're done early. */
   1710 	bp->b_resid = bp->b_bcount;
   1711 	biodone(bp);
   1712 }
   1713 
   1714 /*
   1715  * Queue a drive for I/O.
   1716  */
   1717 void
   1718 eflashstart(void *arg)
   1719 {
   1720 	struct eflash_softc *sc = arg;
   1721 	struct buf *bp = NULL;
   1722 
   1723 	DEBUG_PRINT(("%s: eflashstart\n", device_xname(sc->sc_dev)),
   1724 	    DEBUG_XFERS);
   1725 	while (sc->openings > 0) {
   1726 
   1727 		/* Is there a buf for us ? */
   1728 		if ((bp = bufq_get(sc->sc_q)) == NULL)
   1729 			return;
   1730 
   1731 		/*
   1732 		 * Make the command. First lock the device
   1733 		 */
   1734 		sc->openings--;
   1735 
   1736 		sc->retries = 0;
   1737 		__eflashstart(sc, bp);
   1738 	}
   1739 }
   1740 
   1741 void
   1742 __eflashstart(struct eflash_softc *sc, struct buf *bp)
   1743 {
   1744 	DEBUG_PRINT(("%s: __eflashstart %p\n", device_xname(sc->sc_dev), bp),
   1745 	    DEBUG_XFERS);
   1746 
   1747 	sc->sc_bp = bp;
   1748 	/*
   1749 	 * If we're retrying, retry in single-sector mode. This will give us
   1750 	 * the sector number of the problem, and will eventually allow the
   1751 	 * transfer to succeed.
   1752 	 */
   1753 	if (sc->retries >= EFLASHIORETRIES_SINGLE)
   1754 		sc->sc_bio.flags = ATA_SINGLE;
   1755 	else
   1756 		sc->sc_bio.flags = 0;
   1757 	if (bp->b_flags & B_READ)
   1758 		sc->sc_bio.flags |= ATA_READ;
   1759 	sc->sc_bio.blkno = bp->b_rawblkno;
   1760 	sc->sc_bio.blkdone = 0;
   1761 	sc->sc_bio.nbytes = bp->b_bcount;
   1762 	sc->sc_bio.nblks  = bp->b_bcount >> DEV_BSHIFT;
   1763 	sc->sc_bio.databuf = bp->b_data;
   1764 	/* Instrumentation. */
   1765 	disk_busy(&sc->sc_dk);
   1766     sc->active_xfer = bp;
   1767     wakeup(&sc->ch_thread);
   1768 }
   1769 
   1770 void
   1771 eflashdone(struct eflash_softc *sc)
   1772 {
   1773 	struct buf *bp = sc->sc_bp;
   1774 	const char *errmsg;
   1775 	int do_perror = 0;
   1776 
   1777 	DEBUG_PRINT(("%s: eflashdone %p\n", device_xname(sc->sc_dev), bp),
   1778 	    DEBUG_XFERS);
   1779 
   1780 	if (bp == NULL)
   1781 		return;
   1782 
   1783 	bp->b_resid = sc->sc_bio.nbytes;
   1784 	switch (sc->sc_bio.error) {
   1785 	case ETIMEDOUT:
   1786 		errmsg = "device timeout";
   1787         do_perror = 1;
   1788 		goto retry;
   1789 	case EBUSY:
   1790 		errmsg = "device stuck";
   1791 retry:		/* Just reset and retry. Can we do more ? */
   1792 		/*eflash_reset(sc);*/
   1793 		diskerr(bp, "flash", errmsg, LOG_PRINTF,
   1794 		    sc->sc_bio.blkdone, sc->sc_dk.dk_label);
   1795 		if (sc->retries < EFLASHIORETRIES)
   1796 			printf(", retrying");
   1797 		printf("\n");
   1798 		if (do_perror)
   1799 			eflashperror(sc);
   1800 		if (sc->retries < EFLASHIORETRIES) {
   1801 			sc->retries++;
   1802 			callout_reset(&sc->sc_restart_ch, RECOVERYTIME,
   1803 			    eflashrestart, sc);
   1804 			return;
   1805 		}
   1806 
   1807 		bp->b_error = EIO;
   1808 		break;
   1809 	case 0:
   1810         if ((sc->sc_bio.flags & ATA_CORR) || sc->retries > 0)
   1811 			printf("%s: soft error (corrected)\n",
   1812 			    device_xname(sc->sc_dev));
   1813 		break;
   1814 	case ENODEV:
   1815 	case E2BIG:
   1816 		bp->b_error = EIO;
   1817 		break;
   1818 	}
   1819 	disk_unbusy(&sc->sc_dk, (bp->b_bcount - bp->b_resid),
   1820 	    (bp->b_flags & B_READ));
   1821 	rnd_add_uint32(&sc->rnd_source, bp->b_blkno);
   1822     biodone(bp);
   1823     sc->openings++;
   1824 	eflashstart(sc);
   1825 }
   1826 
   1827 void
   1828 eflashrestart(void *v)
   1829 {
   1830 	struct eflash_softc *sc = v;
   1831 	struct buf *bp = sc->sc_bp;
   1832 	int s;
   1833 	DEBUG_PRINT(("%s: eflashrestart\n", device_xname(sc->sc_dev)),
   1834 	    DEBUG_XFERS);
   1835 
   1836 	s = splbio();
   1837 	__eflashstart(v, bp);
   1838 	splx(s);
   1839 }
   1840 
   1841 int
   1842 eflashread(dev_t dev, struct uio *uio, int flags)
   1843 {
   1844 	DEBUG_PRINT(("eflashread\n"), DEBUG_XFERS);
   1845 	return (physio(eflashstrategy, NULL, dev, B_READ, minphys, uio));
   1846 }
   1847 
   1848 int
   1849 eflashwrite(dev_t dev, struct uio *uio, int flags)
   1850 {
   1851 	DEBUG_PRINT(("eflashwrite\n"), DEBUG_XFERS);
   1852 	return (physio(eflashstrategy, NULL, dev, B_WRITE, minphys, uio));
   1853 }
   1854 
   1855 int
   1856 eflashopen(dev_t dev, int flag, int fmt, struct lwp *l)
   1857 {
   1858 	struct eflash_softc *sc;
   1859 	int part, error;
   1860 
   1861 	DEBUG_PRINT(("eflashopen %" PRIx64 "\n", dev), DEBUG_FUNCS);
   1862 	sc = device_lookup_private(&eflash_cd, EFLASHUNIT(dev));
   1863 	if (sc == NULL)
   1864 		return (ENXIO);
   1865 
   1866 	if (! device_is_active(sc->sc_dev))
   1867 		return (ENODEV);
   1868 
   1869 	part = EFLASHPART(dev);
   1870 
   1871 	mutex_enter(&sc->sc_dk.dk_openlock);
   1872 
   1873 	/*
   1874 	 * If there are wedges, and this is not RAW_PART, then we
   1875 	 * need to fail.
   1876 	 */
   1877 	if (sc->sc_dk.dk_nwedges != 0 && part != RAW_PART) {
   1878 		error = EBUSY;
   1879 		goto bad;
   1880 	}
   1881 
   1882 	if (sc->sc_dk.dk_openmask != 0) {
   1883 		/*
   1884 		 * If any partition is open, but the disk has been invalidated,
   1885 		 * disallow further opens.
   1886 		 */
   1887 		if ((sc->sc_flags & EFLASHF_LOADED) == 0) {
   1888 			error = EIO;
   1889 			goto bad;
   1890 		}
   1891 	} else {
   1892 		if ((sc->sc_flags & EFLASHF_LOADED) == 0) {
   1893 			sc->sc_flags |= EFLASHF_LOADED;
   1894 
   1895 			/* Load the partition info if not already loaded. */
   1896 			eflashgetdisklabel(sc);
   1897 		}
   1898 	}
   1899 
   1900 	/* Check that the partition exists. */
   1901 	if (part != RAW_PART &&
   1902 	    (part >= sc->sc_dk.dk_label->d_npartitions ||
   1903 	     sc->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
   1904 		error = ENXIO;
   1905 		goto bad;
   1906 	}
   1907 
   1908 	/* Insure only one open at a time. */
   1909 	switch (fmt) {
   1910 	case S_IFCHR:
   1911 		sc->sc_dk.dk_copenmask |= (1 << part);
   1912 		break;
   1913 	case S_IFBLK:
   1914 		sc->sc_dk.dk_bopenmask |= (1 << part);
   1915 		break;
   1916 	}
   1917 	sc->sc_dk.dk_openmask =
   1918 	    sc->sc_dk.dk_copenmask | sc->sc_dk.dk_bopenmask;
   1919 
   1920 	mutex_exit(&sc->sc_dk.dk_openlock);
   1921 	return 0;
   1922 
   1923  bad:
   1924 	mutex_exit(&sc->sc_dk.dk_openlock);
   1925 	DEBUG_PRINT(("%s: eflashopen -> %d\n", device_xname(sc->sc_dev), error),
   1926 	    DEBUG_XFERS);
   1927 	return error;
   1928 }
   1929 
   1930 int
   1931 eflashclose(dev_t dev, int flag, int fmt, struct lwp *l)
   1932 {
   1933 	struct eflash_softc *sc = device_lookup_private(&eflash_cd, EFLASHUNIT(dev));
   1934 	int part = EFLASHPART(dev);
   1935 
   1936 	DEBUG_PRINT(("eflashclose %" PRIx64 "\n", dev), DEBUG_FUNCS);
   1937 
   1938 	mutex_enter(&sc->sc_dk.dk_openlock);
   1939 
   1940 	switch (fmt) {
   1941 	case S_IFCHR:
   1942 		sc->sc_dk.dk_copenmask &= ~(1 << part);
   1943 		break;
   1944 	case S_IFBLK:
   1945 		sc->sc_dk.dk_bopenmask &= ~(1 << part);
   1946 		break;
   1947 	}
   1948 	sc->sc_dk.dk_openmask =
   1949 	    sc->sc_dk.dk_copenmask | sc->sc_dk.dk_bopenmask;
   1950 
   1951 	if (sc->sc_dk.dk_openmask == 0) {
   1952 
   1953 		if (! (sc->sc_flags & EFLASHF_KLABEL))
   1954 			sc->sc_flags &= ~EFLASHF_LOADED;
   1955 
   1956         DEBUG_PRINT(("%s: eflashclose flg %x\n", device_xname(sc->sc_dev), sc->sc_flags),
   1957                     DEBUG_XFERS);
   1958 
   1959 	}
   1960 
   1961 	mutex_exit(&sc->sc_dk.dk_openlock);
   1962 	return 0;
   1963 }
   1964 
   1965 void
   1966 eflashgetdefaultlabel(struct eflash_softc *sc, struct disklabel *lp)
   1967 {
   1968 
   1969 	DEBUG_PRINT(("%s: eflashgetdefaultlabel\n", device_xname(sc->sc_dev)), DEBUG_FUNCS);
   1970 	memset(lp, 0, sizeof(struct disklabel));
   1971 
   1972 	lp->d_secsize = DEV_BSIZE;
   1973 	lp->d_ntracks = 1;
   1974 	lp->d_nsectors = sc->sc_capacity;
   1975 	lp->d_ncylinders = 1;
   1976 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1977 
   1978 	lp->d_type = DKTYPE_ST506; /* ?!? */
   1979 
   1980 	strncpy(lp->d_typename, ST506, 16);
   1981 	strncpy(lp->d_packname, "fictitious", 16);
   1982 	if (sc->sc_capacity > UINT32_MAX)
   1983 		lp->d_secperunit = UINT32_MAX;
   1984 	else
   1985 		lp->d_secperunit = sc->sc_capacity;
   1986 	lp->d_rpm = 3600;
   1987 	lp->d_interleave = 1;
   1988 	lp->d_flags = 0;
   1989 
   1990 	lp->d_partitions[RAW_PART].p_offset = 0;
   1991 	lp->d_partitions[RAW_PART].p_size =
   1992 	    lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
   1993 	lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
   1994 	lp->d_npartitions = RAW_PART + 1;
   1995 
   1996 	lp->d_magic = DISKMAGIC;
   1997 	lp->d_magic2 = DISKMAGIC;
   1998 	lp->d_checksum = dkcksum(lp);
   1999 }
   2000 
   2001 /*
   2002  * Fabricate a default disk label, and try to read the correct one.
   2003  */
   2004 void
   2005 eflashgetdisklabel(struct eflash_softc *sc)
   2006 {
   2007 	struct disklabel *lp = sc->sc_dk.dk_label;
   2008 	const char *errstring;
   2009 
   2010 	DEBUG_PRINT(("%s: eflashgetdisklabel\n",  device_xname(sc->sc_dev)), DEBUG_FUNCS);
   2011 
   2012 	memset(sc->sc_dk.dk_cpulabel, 0, sizeof(struct cpu_disklabel));
   2013 
   2014 	eflashgetdefaultlabel(sc, lp);
   2015 
   2016     /* BUGBUG: maj==0?? why is this not EFLASHLABELDEV(??sc->sc_dev) */
   2017 	errstring = readdisklabel(MAKEEFLASHDEV(0, device_unit(sc->sc_dev),
   2018 				  RAW_PART), eflashstrategy, lp,
   2019 				  sc->sc_dk.dk_cpulabel);
   2020 	if (errstring) {
   2021 		printf("%s: %s\n", device_xname(sc->sc_dev), errstring);
   2022 		return;
   2023 	}
   2024 
   2025 #if DEBUG
   2026     if (EFLASH_DEBUG(DEBUG_WRITES)) {
   2027         int i, n = sc->sc_dk.dk_label->d_npartitions;
   2028         printf("%s: %d parts\n", device_xname(sc->sc_dev), n);
   2029         for (i = 0; i < n; i++) {
   2030             printf("\t[%d]: t=%x s=%d o=%d\n", i,
   2031                    sc->sc_dk.dk_label->d_partitions[i].p_fstype,
   2032                    sc->sc_dk.dk_label->d_partitions[i].p_size,
   2033                    sc->sc_dk.dk_label->d_partitions[i].p_offset);
   2034         }
   2035     }
   2036 #endif
   2037 }
   2038 
   2039 void
   2040 eflashperror(const struct eflash_softc *sc)
   2041 {
   2042 	const char *devname = device_xname(sc->sc_dev);
   2043 	u_int32_t Status = sc->sc_bio.r_error;
   2044 
   2045 	printf("%s: (", devname);
   2046 
   2047 	if (Status == 0)
   2048 		printf("error not notified");
   2049 	else
   2050 		printf("status=x%x", Status);
   2051 
   2052 	printf(")\n");
   2053 }
   2054 
   2055 int
   2056 eflashioctl(dev_t dev, u_long xfer, void *addr, int flag, struct lwp *l)
   2057 {
   2058 	struct eflash_softc *sc = device_lookup_private(&eflash_cd, EFLASHUNIT(dev));
   2059 	int error = 0, s;
   2060 
   2061 	DEBUG_PRINT(("eflashioctl(%lx)\n",xfer), DEBUG_FUNCS);
   2062 
   2063 	if ((sc->sc_flags & EFLASHF_LOADED) == 0)
   2064 		return EIO;
   2065 
   2066 	error = disk_ioctl(&sc->sc_dk, dev, xfer, addr, flag, l);
   2067 	if (error != EPASSTHROUGH)
   2068 		return (error);
   2069 
   2070 	switch (xfer) {
   2071 
   2072 	case DIOCWDINFO:
   2073 	case DIOCSDINFO:
   2074 	{
   2075 		struct disklabel *lp;
   2076 
   2077 		if ((flag & FWRITE) == 0)
   2078 			return EBADF;
   2079 
   2080 		lp = (struct disklabel *)addr;
   2081 
   2082 		mutex_enter(&sc->sc_dk.dk_openlock);
   2083 		sc->sc_flags |= EFLASHF_LABELLING;
   2084 
   2085 		error = setdisklabel(sc->sc_dk.dk_label,
   2086 		    lp, /*sc->sc_dk.dk_openmask : */0,
   2087 		    sc->sc_dk.dk_cpulabel);
   2088 		if (error == 0) {
   2089 			if (xfer == DIOCWDINFO)
   2090 				error = writedisklabel(EFLASHLABELDEV(dev),
   2091 				    eflashstrategy, sc->sc_dk.dk_label,
   2092 				    sc->sc_dk.dk_cpulabel);
   2093 		}
   2094 
   2095 		sc->sc_flags &= ~EFLASHF_LABELLING;
   2096 		mutex_exit(&sc->sc_dk.dk_openlock);
   2097 		return error;
   2098 	}
   2099 
   2100 	case DIOCKLABEL:
   2101 		if (*(int *)addr)
   2102 			sc->sc_flags |= EFLASHF_KLABEL;
   2103 		else
   2104 			sc->sc_flags &= ~EFLASHF_KLABEL;
   2105 		return 0;
   2106 
   2107 	case DIOCWLABEL:
   2108 		if ((flag & FWRITE) == 0)
   2109 			return EBADF;
   2110 		if (*(int *)addr)
   2111 			sc->sc_flags |= EFLASHF_WLABEL;
   2112 		else
   2113 			sc->sc_flags &= ~EFLASHF_WLABEL;
   2114 		return 0;
   2115 
   2116 	case DIOCGDEFLABEL:
   2117 		eflashgetdefaultlabel(sc, (struct disklabel *)addr);
   2118 		return 0;
   2119 
   2120 	case DIOCCACHESYNC:
   2121 		return 0;
   2122 
   2123 	case DIOCGSTRATEGY:
   2124 	    {
   2125 		struct disk_strategy *dks = (void *)addr;
   2126 
   2127 		s = splbio();
   2128 		strlcpy(dks->dks_name, bufq_getstrategyname(sc->sc_q),
   2129 		    sizeof(dks->dks_name));
   2130 		splx(s);
   2131 		dks->dks_paramlen = 0;
   2132 
   2133 		return 0;
   2134 	    }
   2135 
   2136 	case DIOCSSTRATEGY:
   2137 	    {
   2138 		struct disk_strategy *dks = (void *)addr;
   2139 		struct bufq_state *new;
   2140 		struct bufq_state *old;
   2141 
   2142 		if ((flag & FWRITE) == 0) {
   2143 			return EBADF;
   2144 		}
   2145 		if (dks->dks_param != NULL) {
   2146 			return EINVAL;
   2147 		}
   2148 		dks->dks_name[sizeof(dks->dks_name) - 1] = 0; /* ensure term */
   2149 		error = bufq_alloc(&new, dks->dks_name,
   2150 		    BUFQ_EXACT|BUFQ_SORT_RAWBLOCK);
   2151 		if (error) {
   2152 			return error;
   2153 		}
   2154 		s = splbio();
   2155 		old = sc->sc_q;
   2156 		bufq_move(new, old);
   2157 		sc->sc_q = new;
   2158 		splx(s);
   2159 		bufq_free(old);
   2160 
   2161 		return 0;
   2162 	    }
   2163 
   2164 	default:
   2165         /* NB: we get a DIOCGWEDGEINFO, but nobody else handles it either */
   2166         DEBUG_PRINT(("eflashioctl: unsup x%lx\n", xfer), DEBUG_FUNCS);
   2167 		return ENOTTY;
   2168 	}
   2169 }
   2170 
   2171 int
   2172 eflashsize(dev_t dev)
   2173 {
   2174 	struct eflash_softc *sc;
   2175 	int part, omask;
   2176 	int size;
   2177 
   2178 	DEBUG_PRINT(("eflashsize\n"), DEBUG_FUNCS);
   2179 
   2180 	sc = device_lookup_private(&eflash_cd, EFLASHUNIT(dev));
   2181 	if (sc == NULL)
   2182 		return (-1);
   2183 
   2184 	part = EFLASHPART(dev);
   2185 	omask = sc->sc_dk.dk_openmask & (1 << part);
   2186 
   2187 	if (omask == 0 && eflashopen(dev, 0, S_IFBLK, NULL) != 0)
   2188 		return (-1);
   2189 	if (sc->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
   2190 		size = -1;
   2191 	else
   2192 		size = sc->sc_dk.dk_label->d_partitions[part].p_size *
   2193 		    (sc->sc_dk.dk_label->d_secsize / DEV_BSIZE);
   2194 	if (omask == 0 && eflashclose(dev, 0, S_IFBLK, NULL) != 0)
   2195 		return (-1);
   2196 	return (size);
   2197 }
   2198 
   2199 /*
   2200  * Dump core after a system crash.
   2201  */
   2202 int
   2203 eflashdump(dev_t dev, daddr_t blkno, void *va, size_t size)
   2204 {
   2205     /* no we dont */
   2206     return (ENXIO);
   2207 }
   2208 
   2209 static void
   2210 eflash_set_geometry(struct eflash_softc *sc)
   2211 {
   2212 	struct disk_geom *dg = &sc->sc_dk.dk_geom;
   2213 
   2214 	memset(dg, 0, sizeof(*dg));
   2215 
   2216 	dg->dg_secperunit = sc->sc_capacity;
   2217 	dg->dg_secsize = DEV_BSIZE /* XXX 512? */;
   2218 	dg->dg_nsectors = sc->sc_capacity;
   2219 	dg->dg_ntracks = 1;
   2220 	dg->dg_ncylinders = sc->sc_capacity;
   2221 
   2222 	disk_set_info(sc->sc_dev, &sc->sc_dk, ST506);
   2223 }
   2224