Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
/*	$NetBSD: nand.c,v 1.27 2017/11/13 17:36:39 jmcneill Exp $	*/

/*-
 * Copyright (c) 2010 Department of Software Engineering,
 *		      University of Szeged, Hungary
 * Copyright (c) 2010 Adam Hoka <ahoka@NetBSD.org>
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by the Department of Software Engineering, University of Szeged, Hungary
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/* Common driver for NAND chips implementing the ONFI 2.2 specification */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: nand.c,v 1.27 2017/11/13 17:36:39 jmcneill Exp $");

#include "locators.h"

#include <sys/param.h>
#include <sys/types.h>
#include <sys/device.h>
#include <sys/kmem.h>
#include <sys/atomic.h>

#include <dev/flash/flash.h>
#include <dev/flash/flash_io.h>
#include <dev/nand/nand.h>
#include <dev/nand/onfi.h>
#include <dev/nand/hamming.h>
#include <dev/nand/nand_bbt.h>
#include <dev/nand/nand_crc.h>

#include "opt_nand.h"

int nand_match(device_t, cfdata_t, void *);
void nand_attach(device_t, device_t, void *);
int nand_detach(device_t, int);
bool nand_shutdown(device_t, int);

int nand_print(void *, const char *);

static int nand_search(device_t, cfdata_t, const int *, void *);
static void nand_address_row(device_t, size_t);
static inline uint8_t nand_get_status(device_t);
static void nand_address_column(device_t, size_t, size_t);
static int nand_fill_chip_structure(device_t, struct nand_chip *);
static int nand_scan_media(device_t, struct nand_chip *);
static bool nand_check_wp(device_t);

CFATTACH_DECL_NEW(nand, sizeof(struct nand_softc),
    nand_match, nand_attach, nand_detach, NULL);

#ifdef NAND_DEBUG
int	nanddebug = NAND_DEBUG;
#endif

struct flash_interface nand_flash_if = {
	.type = FLASH_TYPE_NAND,

	.read = nand_flash_read,
	.write = nand_flash_write,
	.erase = nand_flash_erase,
	.block_isbad = nand_flash_isbad,
	.block_markbad = nand_flash_markbad,

	.submit = nand_flash_submit
};

const struct nand_manufacturer nand_mfrs[] = {
	{ NAND_MFR_AMD,		"AMD" },
	{ NAND_MFR_FUJITSU,	"Fujitsu" },
	{ NAND_MFR_RENESAS,	"Renesas" },
	{ NAND_MFR_STMICRO,	"ST Micro" },
	{ NAND_MFR_MICRON,	"Micron" },
	{ NAND_MFR_NATIONAL,	"National" },
	{ NAND_MFR_TOSHIBA,	"Toshiba" },
	{ NAND_MFR_HYNIX,	"Hynix" },
	{ NAND_MFR_SAMSUNG,	"Samsung" },
	{ NAND_MFR_UNKNOWN,	"Unknown" }
};

static const char *
nand_midtoname(int id)
{
	int i;

	for (i = 0; nand_mfrs[i].id != 0; i++) {
		if (nand_mfrs[i].id == id)
			return nand_mfrs[i].name;
	}

	KASSERT(nand_mfrs[i].id == 0);

	return nand_mfrs[i].name;
}

/* ARGSUSED */
int
nand_match(device_t parent, cfdata_t match, void *aux)
{
	/* pseudo device, always attaches */
	return 1;
}

void
nand_attach(device_t parent, device_t self, void *aux)
{
	struct nand_softc *sc = device_private(self);
	struct nand_attach_args *naa = aux;
	struct nand_chip *chip = &sc->sc_chip;

	sc->sc_dev = self;
	sc->controller_dev = parent;
	sc->nand_if = naa->naa_nand_if;

	aprint_naive("\n");

	if (nand_check_wp(self)) {
		aprint_error("NAND chip is write protected!\n");
		return;
	}

	if (nand_scan_media(self, chip)) {
		return;
	}

	nand_flash_if.erasesize = chip->nc_block_size;
	nand_flash_if.page_size = chip->nc_page_size;
	nand_flash_if.writesize = chip->nc_page_size;

	/* allocate cache */
	chip->nc_oob_cache = kmem_alloc(chip->nc_spare_size, KM_SLEEP);
	chip->nc_page_cache = kmem_alloc(chip->nc_page_size, KM_SLEEP);

	mutex_init(&sc->sc_device_lock, MUTEX_DEFAULT, IPL_NONE);

	if (flash_sync_thread_init(&sc->sc_flash_io, self, &nand_flash_if)) {
		goto error;
	}

	if (!pmf_device_register1(sc->sc_dev, NULL, NULL, nand_shutdown))
		aprint_error_dev(sc->sc_dev,
		    "couldn't establish power handler\n");

#ifdef NAND_BBT
	nand_bbt_init(self);
	nand_bbt_scan(self);
#endif

	/*
	 * Attach all our devices
	 */
	config_search_ia(nand_search, self, NULL, NULL);

	return;
error:
	kmem_free(chip->nc_oob_cache, chip->nc_spare_size);
	kmem_free(chip->nc_page_cache, chip->nc_page_size);
	mutex_destroy(&sc->sc_device_lock);
}

static int
nand_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
{
	struct nand_softc *sc = device_private(parent);
	struct nand_chip *chip = &sc->sc_chip;
	struct flash_attach_args faa;

	if (cf->cf_loc[FLASHBUSCF_DYNAMIC] != 0)
		return 0;

	faa.flash_if = &nand_flash_if;

	faa.partinfo.part_name = NULL;
	faa.partinfo.part_offset = cf->cf_loc[FLASHBUSCF_OFFSET];

	if (cf->cf_loc[FLASHBUSCF_SIZE] == 0) {
		faa.partinfo.part_size = chip->nc_size -
		    faa.partinfo.part_offset;
	} else {
		faa.partinfo.part_size = cf->cf_loc[FLASHBUSCF_SIZE];
	}

	if (cf->cf_loc[FLASHBUSCF_READONLY])
		faa.partinfo.part_flags = FLASH_PART_READONLY;
	else
		faa.partinfo.part_flags = 0;

	if (config_match(parent, cf, &faa)) {
		if (config_attach(parent, cf, &faa, nand_print) != NULL) {
			return 0;
		} else {
			return 1;
		}
	}

	return 1;
}

void
nand_attach_mtdparts(device_t parent, const char *mtd_id, const char *cmdline)
{
	struct nand_softc *sc = device_private(parent);
	struct nand_chip *chip = &sc->sc_chip;

	flash_attach_mtdparts(&nand_flash_if, parent, chip->nc_size,
	    mtd_id, cmdline);
}

int
nand_detach(device_t self, int flags)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	int error = 0;

	error = config_detach_children(self, flags);
	if (error) {
		return error;
	}

	flash_sync_thread_destroy(&sc->sc_flash_io);
#ifdef NAND_BBT
	nand_bbt_detach(self);
#endif
	/* free oob cache */
	kmem_free(chip->nc_oob_cache, chip->nc_spare_size);
	kmem_free(chip->nc_page_cache, chip->nc_page_size);
	kmem_free(chip->nc_ecc_cache, chip->nc_ecc->necc_size);

	mutex_destroy(&sc->sc_device_lock);

	pmf_device_deregister(sc->sc_dev);

	return error;
}

int
nand_print(void *aux, const char *pnp)
{
	if (pnp != NULL)
		aprint_normal("nand at %s\n", pnp);

	return UNCONF;
}

/* ask for a nand driver to attach to the controller */
device_t
nand_attach_mi(struct nand_interface *nand_if, device_t parent)
{
	struct nand_attach_args arg;

	KASSERT(nand_if != NULL);

	/* fill the defaults if we have null pointers */
	if (nand_if->program_page == NULL) {
		nand_if->program_page = &nand_default_program_page;
	}

	if (nand_if->read_page == NULL) {
		nand_if->read_page = &nand_default_read_page;
	}

	arg.naa_nand_if = nand_if;
	return config_found_ia(parent, "nandbus", &arg, nand_print);
}

/* default everything to reasonable values, to ease future api changes */
void
nand_init_interface(struct nand_interface *interface)
{
	interface->select = &nand_default_select;
	interface->command = NULL;
	interface->address = NULL;
	interface->read_buf_1 = NULL;
	interface->read_buf_2 = NULL;
	interface->read_1 = NULL;
	interface->read_2 = NULL;
	interface->write_buf_1 = NULL;
	interface->write_buf_2 = NULL;
	interface->write_1 = NULL;
	interface->write_2 = NULL;
	interface->busy = NULL;

	/*-
	 * most drivers dont want to change this, but some implement
	 * read/program in one step
	 */
	interface->program_page = &nand_default_program_page;
	interface->read_page = &nand_default_read_page;

	/* default to soft ecc, that should work everywhere */
	interface->ecc_compute = &nand_default_ecc_compute;
	interface->ecc_correct = &nand_default_ecc_correct;
	interface->ecc_prepare = NULL;
	interface->ecc.necc_code_size = 3;
	interface->ecc.necc_block_size = 256;
	interface->ecc.necc_type = NAND_ECC_TYPE_SW;
}

#if 0
/* handle quirks here */
static void
nand_quirks(device_t self, struct nand_chip *chip)
{
	/* this is an example only! */
	switch (chip->nc_manf_id) {
	case NAND_MFR_SAMSUNG:
		if (chip->nc_dev_id == 0x00) {
			/* do something only samsung chips need */
			/* or */
			/* chip->nc_quirks |= NC_QUIRK_NO_READ_START */
		}
	}

	return;
}
#endif

static int
nand_fill_chip_structure_legacy(device_t self, struct nand_chip *chip)
{
	switch (chip->nc_manf_id) {
	case NAND_MFR_MICRON:
		return nand_read_parameters_micron(self, chip);
	case NAND_MFR_SAMSUNG:
		return nand_read_parameters_samsung(self, chip);
	case NAND_MFR_TOSHIBA:
		return nand_read_parameters_toshiba(self, chip);
	default:
		return 1;
	}

	return 0;
}

/**
 * scan media to determine the chip's properties
 * this function resets the device
 */
static int
nand_scan_media(device_t self, struct nand_chip *chip)
{
	struct nand_softc *sc = device_private(self);
	struct nand_ecc *ecc;
	uint8_t onfi_signature[4];

	nand_select(self, true);
	nand_command(self, ONFI_RESET);
	KASSERT(nand_get_status(self) & ONFI_STATUS_RDY);
	nand_select(self, false);

	/* check if the device implements the ONFI standard */
	nand_select(self, true);
	nand_command(self, ONFI_READ_ID);
	nand_address(self, 0x20);
	nand_read_1(self, &onfi_signature[0]);
	nand_read_1(self, &onfi_signature[1]);
	nand_read_1(self, &onfi_signature[2]);
	nand_read_1(self, &onfi_signature[3]);
	nand_select(self, false);

#ifdef NAND_DEBUG
	device_printf(self, "signature: %02x %02x %02x %02x\n",
	    onfi_signature[0], onfi_signature[1],
	    onfi_signature[2], onfi_signature[3]);
#endif

	if (onfi_signature[0] != 'O' || onfi_signature[1] != 'N' ||
	    onfi_signature[2] != 'F' || onfi_signature[3] != 'I') {
		chip->nc_isonfi = false;

		aprint_normal(": Legacy NAND Flash\n");

		nand_read_id(self, &chip->nc_manf_id, &chip->nc_dev_id);

		if (nand_fill_chip_structure_legacy(self, chip)) {
			aprint_error_dev(self,
			    "can't read device parameters for legacy chip\n");
			return 1;
		}
	} else {
		chip->nc_isonfi = true;

		aprint_normal(": ONFI NAND Flash\n");

		nand_read_id(self, &chip->nc_manf_id, &chip->nc_dev_id);

		if (nand_fill_chip_structure(self, chip)) {
			aprint_error_dev(self,
			    "can't read device parameters\n");
			return 1;
		}
	}

	aprint_normal_dev(self,
	    "manufacturer id: 0x%.2x (%s), device id: 0x%.2x\n",
	    chip->nc_manf_id,
	    nand_midtoname(chip->nc_manf_id),
	    chip->nc_dev_id);

	aprint_normal_dev(self,
	    "page size: %" PRIu32 " bytes, spare size: %" PRIu32 " bytes, "
	    "block size: %" PRIu32 " bytes\n",
	    chip->nc_page_size, chip->nc_spare_size, chip->nc_block_size);

	aprint_normal_dev(self,
	    "LUN size: %" PRIu32 " blocks, LUNs: %" PRIu8
	    ", total storage size: %" PRIu64 " MB\n",
	    chip->nc_lun_blocks, chip->nc_num_luns,
	    chip->nc_size / 1024 / 1024);

	aprint_normal_dev(self, "column cycles: %" PRIu8 ", row cycles: %"
	    PRIu8 ", width: %s\n",
	    chip->nc_addr_cycles_column, chip->nc_addr_cycles_row,
	    (chip->nc_flags & NC_BUSWIDTH_16) ? "x16" : "x8");

	ecc = chip->nc_ecc = &sc->nand_if->ecc;

	/*
	 * calculate the place of ecc data in oob
	 * we try to be compatible with Linux here
	 */
	switch (chip->nc_spare_size) {
	case 8:
		ecc->necc_offset = 0;
		break;
	case 16:
		ecc->necc_offset = 0;
		break;
	case 32:
		ecc->necc_offset = 0;
		break;
	case 64:
		ecc->necc_offset = 40;
		break;
	case 128:
		ecc->necc_offset = 80;
		break;
	default:
		panic("OOB size %" PRIu32 " is unexpected", chip->nc_spare_size);
	}

	ecc->necc_steps = chip->nc_page_size / ecc->necc_block_size;
	ecc->necc_size = ecc->necc_steps * ecc->necc_code_size;

	/* check if we fit in oob */
	if (ecc->necc_offset + ecc->necc_size > chip->nc_spare_size) {
		panic("NAND ECC bits dont fit in OOB");
	}

	/* TODO: mark free oob area available for file systems */

	chip->nc_ecc_cache = kmem_zalloc(ecc->necc_size, KM_SLEEP);

	/*
	 * calculate badblock marker offset in oob
	 * we try to be compatible with linux here
	 */
	if (chip->nc_page_size > 512)
		chip->nc_badmarker_offs = 0;
	else
		chip->nc_badmarker_offs = 5;

	/* Calculate page shift and mask */
	chip->nc_page_shift = ffs(chip->nc_page_size) - 1;
	chip->nc_page_mask = ~(chip->nc_page_size - 1);
	/* same for block */
	chip->nc_block_shift = ffs(chip->nc_block_size) - 1;
	chip->nc_block_mask = ~(chip->nc_block_size - 1);

	/* look for quirks here if needed in future */
	/* nand_quirks(self, chip); */

	return 0;
}

void
nand_read_id(device_t self, uint8_t *manf, uint8_t *dev)
{
	nand_select(self, true);
	nand_command(self, ONFI_READ_ID);
	nand_address(self, 0x00);

	nand_read_1(self, manf);
	nand_read_1(self, dev);

	nand_select(self, false);
}

int
nand_read_parameter_page(device_t self, struct onfi_parameter_page *params)
{
	uint8_t *bufp;
	uint16_t crc;
	int i;//, tries = 0;

	KASSERT(sizeof(*params) == 256);

//read_params:
//	tries++;

	nand_select(self, true);
	nand_command(self, ONFI_READ_PARAMETER_PAGE);
	nand_address(self, 0x00);

	nand_busy(self);

	/* TODO check the signature if it contains at least 2 letters */

	bufp = (uint8_t *)params;
	/* XXX why i am not using read_buf? */
	for (i = 0; i < 256; i++) {
		nand_read_1(self, &bufp[i]);
	}
	nand_select(self, false);

	/* validate the parameter page with the crc */
	crc = nand_crc16(bufp, 254);

	if (crc != params->param_integrity_crc) {
		aprint_error_dev(self, "parameter page crc check failed\n");
		/* TODO: we should read the next parameter page copy */
		return 1;
	}

	return 0;
}

static int
nand_fill_chip_structure(device_t self, struct nand_chip *chip)
{
	struct onfi_parameter_page params;
	uint8_t	vendor[13], model[21];
	int i;

	if (nand_read_parameter_page(self, &params)) {
		return 1;
	}

	/* strip manufacturer and model string */
	strlcpy(vendor, params.param_manufacturer, sizeof(vendor));
	for (i = 11; i > 0 && vendor[i] == ' '; i--)
		vendor[i] = 0;
	strlcpy(model, params.param_model, sizeof(model));
	for (i = 19; i > 0 && model[i] == ' '; i--)
		model[i] = 0;

	aprint_normal_dev(self, "vendor: %s, model: %s\n", vendor, model);

	chip->nc_page_size = le32toh(params.param_pagesize);
	chip->nc_block_size =
	    le32toh(params.param_blocksize) * chip->nc_page_size;
	chip->nc_spare_size = le16toh(params.param_sparesize);
	chip->nc_lun_blocks = le32toh(params.param_lunsize);
	chip->nc_num_luns = params.param_numluns;

	chip->nc_size =
	    chip->nc_block_size * chip->nc_lun_blocks * chip->nc_num_luns;

	/* the lower 4 bits contain the row address cycles */
	chip->nc_addr_cycles_row = params.param_addr_cycles & 0x07;
	/* the upper 4 bits contain the column address cycles */
	chip->nc_addr_cycles_column = (params.param_addr_cycles & ~0x07) >> 4;

	uint16_t features = le16toh(params.param_features);
	if (features & ONFI_FEATURE_16BIT) {
		chip->nc_flags |= NC_BUSWIDTH_16;
	}

	if (features & ONFI_FEATURE_EXTENDED_PARAM) {
		chip->nc_flags |= NC_EXTENDED_PARAM;
	}

	return 0;
}

/* ARGSUSED */
bool
nand_shutdown(device_t self, int howto)
{
	return true;
}

static void
nand_address_column(device_t self, size_t row, size_t column)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	uint8_t i;

	DPRINTF(("addressing row: 0x%jx column: %" PRIu32 "\n",
		(uintmax_t )row, column));

	/* XXX TODO */
	row >>= chip->nc_page_shift;

	/* Write the column (subpage) address */
	if (chip->nc_flags & NC_BUSWIDTH_16)
		column >>= 1;
	for (i = 0; i < chip->nc_addr_cycles_column; i++, column >>= 8)
		nand_address(self, column & 0xff);

	/* Write the row (page) address */
	for (i = 0; i < chip->nc_addr_cycles_row; i++, row >>= 8)
		nand_address(self, row & 0xff);
}

static void
nand_address_row(device_t self, size_t row)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	int i;

	/* XXX TODO */
	row >>= chip->nc_page_shift;

	/* Write the row (page) address */
	for (i = 0; i < chip->nc_addr_cycles_row; i++, row >>= 8)
		nand_address(self, row & 0xff);
}

static inline uint8_t
nand_get_status(device_t self)
{
	uint8_t status;

	nand_command(self, ONFI_READ_STATUS);
	nand_busy(self);
	nand_read_1(self, &status);

	return status;
}

static bool
nand_check_wp(device_t self)
{
	if (nand_get_status(self) & ONFI_STATUS_WP)
		return false;
	else
		return true;
}

static void
nand_prepare_read(device_t self, flash_off_t row, flash_off_t column)
{
	nand_command(self, ONFI_READ);
	nand_address_column(self, row, column);
	nand_command(self, ONFI_READ_START);

	nand_busy(self);
}

/* read a page with ecc correction, default implementation */
int
nand_default_read_page(device_t self, size_t offset, uint8_t *data)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	size_t b, bs, e, cs;
	uint8_t *ecc;
	int result;

	nand_prepare_read(self, offset, 0);

	bs = chip->nc_ecc->necc_block_size;
	cs = chip->nc_ecc->necc_code_size;

	/* decide if we access by 8 or 16 bits */
	if (chip->nc_flags & NC_BUSWIDTH_16) {
		for (b = 0, e = 0; b < chip->nc_page_size; b += bs, e += cs) {
			nand_ecc_prepare(self, NAND_ECC_READ);
			nand_read_buf_2(self, data + b, bs);
			nand_ecc_compute(self, data + b,
			    chip->nc_ecc_cache + e);
		}
	} else {
		for (b = 0, e = 0; b < chip->nc_page_size; b += bs, e += cs) {
			nand_ecc_prepare(self, NAND_ECC_READ);
			nand_read_buf_1(self, data + b, bs);
			nand_ecc_compute(self, data + b,
			    chip->nc_ecc_cache + e);
		}
	}

	/* for debugging new drivers */
#if 0
	nand_dump_data("page", data, chip->nc_page_size);
#endif

	nand_read_oob(self, offset, chip->nc_oob_cache);
	ecc = chip->nc_oob_cache + chip->nc_ecc->necc_offset;

	/* useful for debugging new ecc drivers */
#if 0
	printf("dumping ecc %d\n--------------\n", chip->nc_ecc->necc_steps);
	for (e = 0; e < chip->nc_ecc->necc_steps; e++) {
		printf("0x");
		for (b = 0; b < cs; b++) {
			printf("%.2hhx", ecc[e+b]);
		}
		printf(" 0x");
		for (b = 0; b < cs; b++) {
			printf("%.2hhx", chip->nc_ecc_cache[e+b]);
		}
		printf("\n");
	}
	printf("--------------\n");
#endif

	for (b = 0, e = 0; b < chip->nc_page_size; b += bs, e += cs) {
		result = nand_ecc_correct(self, data + b, ecc + e,
		    chip->nc_ecc_cache + e);

		switch (result) {
		case NAND_ECC_OK:
			break;
		case NAND_ECC_CORRECTED:
			aprint_error_dev(self,
			    "data corrected with ECC at page offset 0x%jx "
			    "block %zu\n", (uintmax_t)offset, b);
			break;
		case NAND_ECC_TWOBIT:
			aprint_error_dev(self,
			    "uncorrectable ECC error at page offset 0x%jx "
			    "block %zu\n", (uintmax_t)offset, b);
			return EIO;
			break;
		case NAND_ECC_INVALID:
			aprint_error_dev(self,
			    "invalid ECC in oob at page offset 0x%jx "
			    "block %zu\n", (uintmax_t)offset, b);
			return EIO;
			break;
		default:
			panic("invalid ECC correction errno");
		}
	}

	return 0;
}

int
nand_default_program_page(device_t self, size_t page, const uint8_t *data)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	size_t bs, cs, e, b;
	uint8_t status;
	uint8_t *ecc;

	nand_command(self, ONFI_PAGE_PROGRAM);
	nand_address_column(self, page, 0);

	nand_busy(self);

	bs = chip->nc_ecc->necc_block_size;
	cs = chip->nc_ecc->necc_code_size;
	ecc = chip->nc_oob_cache + chip->nc_ecc->necc_offset;

	/* XXX code duplication */
	/* decide if we access by 8 or 16 bits */
	if (chip->nc_flags & NC_BUSWIDTH_16) {
		for (b = 0, e = 0; b < chip->nc_page_size; b += bs, e += cs) {
			nand_ecc_prepare(self, NAND_ECC_WRITE);
			nand_write_buf_2(self, data + b, bs);
			nand_ecc_compute(self, data + b, ecc + e);
		}
		/* write oob with ecc correction code */
		nand_write_buf_2(self, chip->nc_oob_cache,
		    chip->nc_spare_size);
	} else {
		for (b = 0, e = 0; b < chip->nc_page_size; b += bs, e += cs) {
			nand_ecc_prepare(self, NAND_ECC_WRITE);
			nand_write_buf_1(self, data + b, bs);
			nand_ecc_compute(self, data + b, ecc + e);
		}
		/* write oob with ecc correction code */
		nand_write_buf_1(self, chip->nc_oob_cache,
		    chip->nc_spare_size);
	}

	nand_command(self, ONFI_PAGE_PROGRAM_START);

	nand_busy(self);

	/* for debugging ecc */
#if 0
	printf("dumping ecc %d\n--------------\n", chip->nc_ecc->necc_steps);
	for (e = 0; e < chip->nc_ecc->necc_steps; e++) {
		printf("0x");
		for (b = 0; b < cs; b++) {
			printf("%.2hhx", ecc[e+b]);
		}
		printf("\n");
	}
	printf("--------------\n");
#endif

	status = nand_get_status(self);
	KASSERT(status & ONFI_STATUS_RDY);
	if (status & ONFI_STATUS_FAIL) {
		aprint_error_dev(self, "page program failed!\n");
		return EIO;
	}

	return 0;
}

/* read the OOB of a page */
int
nand_read_oob(device_t self, size_t page, uint8_t *oob)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;

	nand_prepare_read(self, page, chip->nc_page_size);

	if (chip->nc_flags & NC_BUSWIDTH_16)
		nand_read_buf_2(self, oob, chip->nc_spare_size);
	else
		nand_read_buf_1(self, oob, chip->nc_spare_size);

	/* for debugging drivers */
#if 0
	nand_dump_data("oob", oob, chip->nc_spare_size);
#endif

	return 0;
}

static int
nand_write_oob(device_t self, size_t offset, const void *oob)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	uint8_t status;

	nand_command(self, ONFI_PAGE_PROGRAM);
	nand_address_column(self, offset, chip->nc_page_size);
	nand_command(self, ONFI_PAGE_PROGRAM_START);

	nand_busy(self);

	if (chip->nc_flags & NC_BUSWIDTH_16)
		nand_write_buf_2(self, oob, chip->nc_spare_size);
	else
		nand_write_buf_1(self, oob, chip->nc_spare_size);

	status = nand_get_status(self);
	KASSERT(status & ONFI_STATUS_RDY);
	if (status & ONFI_STATUS_FAIL)
		return EIO;
	else
		return 0;
}

void
nand_markbad(device_t self, size_t offset)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t blockoffset;
#ifdef NAND_BBT
	flash_off_t block;

	block = offset / chip->nc_block_size;

	nand_bbt_block_markbad(self, block);
#endif
	blockoffset = offset & chip->nc_block_mask;

	/* check if it is already marked bad */
	if (nand_isbad(self, blockoffset))
		return;

	nand_read_oob(self, blockoffset, chip->nc_oob_cache);

	chip->nc_oob_cache[chip->nc_badmarker_offs] = 0x00;
	chip->nc_oob_cache[chip->nc_badmarker_offs + 1] = 0x00;

	nand_write_oob(self, blockoffset, chip->nc_oob_cache);
}

bool
nand_isfactorybad(device_t self, flash_off_t offset)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t block, first_page, last_page, page;
	int i;

	/* Check for factory bad blocks first
	 * Factory bad blocks are marked in the first or last
	 * page of the blocks, see: ONFI 2.2, 3.2.2.
	 */
	block = offset / chip->nc_block_size;
	first_page = block * chip->nc_block_size;
	last_page = (block + 1) * chip->nc_block_size
	    - chip->nc_page_size;

	for (i = 0, page = first_page; i < 2; i++, page = last_page) {
		/* address OOB */
		nand_prepare_read(self, page, chip->nc_page_size);

		if (chip->nc_flags & NC_BUSWIDTH_16) {
			uint16_t word;
			nand_read_2(self, &word);
			if (word == 0x0000)
				return true;
		} else {
			uint8_t byte;
			nand_read_1(self, &byte);
			if (byte == 0x00)
				return true;
		}
	}

	return false;
}

bool
nand_iswornoutbad(device_t self, flash_off_t offset)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t block;

	/* we inspect the first page of the block */
	block = offset & chip->nc_block_mask;

	/* Linux/u-boot compatible badblock handling */
	if (chip->nc_flags & NC_BUSWIDTH_16) {
		uint16_t word, mark;

		nand_prepare_read(self, block,
		    chip->nc_page_size + (chip->nc_badmarker_offs & 0xfe));

		nand_read_2(self, &word);
		mark = htole16(word);
		if (chip->nc_badmarker_offs & 0x01)
			mark >>= 8;
		if ((mark & 0xff) != 0xff)
			return true;
	} else {
		uint8_t byte;

		nand_prepare_read(self, block,
		    chip->nc_page_size + chip->nc_badmarker_offs);

		nand_read_1(self, &byte);
		if (byte != 0xff)
			return true;
	}

	return false;
}

bool
nand_isbad(device_t self, flash_off_t offset)
{
#ifdef NAND_BBT
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t block;

	block = offset / chip->nc_block_size;

	return nand_bbt_block_isbad(self, block);
#else
	/* ONFI host requirement */
	if (nand_isfactorybad(self, offset))
		return true;

	/* Look for Linux/U-Boot compatible bad marker */
	if (nand_iswornoutbad(self, offset))
		return true;

	return false;
#endif
}

int
nand_erase_block(device_t self, size_t offset)
{
	uint8_t status;

	/* xxx calculate first page of block for address? */

	nand_command(self, ONFI_BLOCK_ERASE);
	nand_address_row(self, offset);
	nand_command(self, ONFI_BLOCK_ERASE_START);

	nand_busy(self);

	status = nand_get_status(self);
	KASSERT(status & ONFI_STATUS_RDY);
	if (status & ONFI_STATUS_FAIL) {
		aprint_error_dev(self, "block erase failed!\n");
		nand_markbad(self, offset);
		return EIO;
	} else {
		return 0;
	}
}

/* default functions for driver development */

/* default ECC using hamming code of 256 byte chunks */
int
nand_default_ecc_compute(device_t self, const uint8_t *data, uint8_t *code)
{
	hamming_compute_256(data, code);

	return 0;
}

int
nand_default_ecc_correct(device_t self, uint8_t *data, const uint8_t *origcode,
	const uint8_t *compcode)
{
	return hamming_correct_256(data, origcode, compcode);
}

void
nand_default_select(device_t self, bool enable)
{
	/* do nothing */
	return;
}

/* implementation of the block device API */

int
nand_flash_submit(device_t self, struct buf * const bp)
{
	struct nand_softc *sc = device_private(self);

	return flash_io_submit(&sc->sc_flash_io, bp);
}

/*
 * handle (page) unaligned write to nand
 */
static int
nand_flash_write_unaligned(device_t self, flash_off_t offset, size_t len,
    size_t *retlen, const uint8_t *buf)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t first, last, firstoff;
	const uint8_t *bufp;
	flash_off_t addr;
	size_t left, count;
	int error = 0, i;

	first = offset & chip->nc_page_mask;
	firstoff = offset & ~chip->nc_page_mask;
	/* XXX check if this should be len - 1 */
	last = (offset + len) & chip->nc_page_mask;
	count = last - first + 1;

	addr = first;
	*retlen = 0;

	mutex_enter(&sc->sc_device_lock);
	if (count == 1) {
		if (nand_isbad(self, addr)) {
			aprint_error_dev(self,
			    "nand_flash_write_unaligned: "
			    "bad block encountered\n");
			error = EIO;
			goto out;
		}

		error = nand_read_page(self, addr, chip->nc_page_cache);
		if (error) {
			goto out;
		}

		memcpy(chip->nc_page_cache + firstoff, buf, len);

		error = nand_program_page(self, addr, chip->nc_page_cache);
		if (error) {
			goto out;
		}

		*retlen = len;
		goto out;
	}

	bufp = buf;
	left = len;

	for (i = 0; i < count && left != 0; i++) {
		if (nand_isbad(self, addr)) {
			aprint_error_dev(self,
			    "nand_flash_write_unaligned: "
			    "bad block encountered\n");
			error = EIO;
			goto out;
		}

		if (i == 0) {
			error = nand_read_page(self,
			    addr, chip->nc_page_cache);
			if (error) {
				goto out;
			}

			memcpy(chip->nc_page_cache + firstoff,
			    bufp, chip->nc_page_size - firstoff);

			printf("program page: %s: %d\n", __FILE__, __LINE__);
			error = nand_program_page(self,
			    addr, chip->nc_page_cache);
			if (error) {
				goto out;
			}

			bufp += chip->nc_page_size - firstoff;
			left -= chip->nc_page_size - firstoff;
			*retlen += chip->nc_page_size - firstoff;

		} else if (i == count - 1) {
			error = nand_read_page(self,
			    addr, chip->nc_page_cache);
			if (error) {
				goto out;
			}

			memcpy(chip->nc_page_cache, bufp, left);

			error = nand_program_page(self,
			    addr, chip->nc_page_cache);
			if (error) {
				goto out;
			}

			*retlen += left;
			KASSERT(left < chip->nc_page_size);

		} else {
			/* XXX debug */
			if (left > chip->nc_page_size) {
				printf("left: %zu, i: %d, count: %zu\n",
				    left, i, count);
			}
			KASSERT(left > chip->nc_page_size);

			error = nand_program_page(self, addr, bufp);
			if (error) {
				goto out;
			}

			bufp += chip->nc_page_size;
			left -= chip->nc_page_size;
			*retlen += chip->nc_page_size;
		}

		addr += chip->nc_page_size;
	}

	KASSERT(*retlen == len);
out:
	mutex_exit(&sc->sc_device_lock);

	return error;
}

int
nand_flash_write(device_t self, flash_off_t offset, size_t len, size_t *retlen,
    const uint8_t *buf)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	const uint8_t *bufp;
	size_t pages, page;
	daddr_t addr;
	int error = 0;

	if ((offset + len) > chip->nc_size) {
		DPRINTF(("nand_flash_write: write (off: 0x%jx, len: %ju),"
			" is over device size (0x%jx)\n",
			(uintmax_t)offset, (uintmax_t)len,
			(uintmax_t)chip->nc_size));
		return EINVAL;
	}

	if (len % chip->nc_page_size != 0 ||
	    offset % chip->nc_page_size != 0) {
		return nand_flash_write_unaligned(self,
		    offset, len, retlen, buf);
	}

	pages = len / chip->nc_page_size;
	KASSERT(pages != 0);
	*retlen = 0;

	addr = offset;
	bufp = buf;

	mutex_enter(&sc->sc_device_lock);
	for (page = 0; page < pages; page++) {
		/* do we need this check here? */
		if (nand_isbad(self, addr)) {
			aprint_error_dev(self,
			    "nand_flash_write: bad block encountered\n");

			error = EIO;
			goto out;
		}

		error = nand_program_page(self, addr, bufp);
		if (error) {
			goto out;
		}

		addr += chip->nc_page_size;
		bufp += chip->nc_page_size;
		*retlen += chip->nc_page_size;
	}
out:
	mutex_exit(&sc->sc_device_lock);
	DPRINTF(("page programming: retlen: %" PRIu32 ", len: %" PRIu32 "\n", *retlen, len));

	return error;
}

/*
 * handle (page) unaligned read from nand
 */
static int
nand_flash_read_unaligned(device_t self, size_t offset,
    size_t len, size_t *retlen, uint8_t *buf)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	daddr_t first, last, count, firstoff;
	uint8_t *bufp;
	daddr_t addr;
	size_t left;
	int error = 0, i;

	first = offset & chip->nc_page_mask;
	firstoff = offset & ~chip->nc_page_mask;
	last = (offset + len) & chip->nc_page_mask;
	count = (last - first) / chip->nc_page_size + 1;

	addr = first;
	bufp = buf;
	left = len;
	*retlen = 0;

	mutex_enter(&sc->sc_device_lock);
	if (count == 1) {
		error = nand_read_page(self, addr, chip->nc_page_cache);
		if (error) {
			goto out;
		}

		memcpy(bufp, chip->nc_page_cache + firstoff, len);

		*retlen = len;
		goto out;
	}

	for (i = 0; i < count && left != 0; i++) {
		error = nand_read_page(self, addr, chip->nc_page_cache);
		if (error) {
			goto out;
		}

		if (i == 0) {
			memcpy(bufp, chip->nc_page_cache + firstoff,
			    chip->nc_page_size - firstoff);

			bufp += chip->nc_page_size - firstoff;
			left -= chip->nc_page_size - firstoff;
			*retlen += chip->nc_page_size - firstoff;

		} else if (i == count - 1) {
			memcpy(bufp, chip->nc_page_cache, left);
			*retlen += left;
			KASSERT(left < chip->nc_page_size);

		} else {
			memcpy(bufp, chip->nc_page_cache, chip->nc_page_size);

			bufp += chip->nc_page_size;
			left -= chip->nc_page_size;
			*retlen += chip->nc_page_size;
		}

		addr += chip->nc_page_size;
	}
	KASSERT(*retlen == len);
out:
	mutex_exit(&sc->sc_device_lock);

	return error;
}

int
nand_flash_read(device_t self, flash_off_t offset, size_t len, size_t *retlen,
    uint8_t *buf)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	uint8_t *bufp;
	size_t addr;
	size_t i, pages;
	int error = 0;

	*retlen = 0;

	DPRINTF(("nand_flash_read: off: 0x%jx, len: %" PRIu32 "\n",
		(uintmax_t)offset, len));

	if (__predict_false((offset + len) > chip->nc_size)) {
		DPRINTF(("nand_flash_read: read (off: 0x%jx, len: %" PRIu32 "),"
			" is over device size (%ju)\n", (uintmax_t)offset,
			len, (uintmax_t)chip->nc_size));
		return EINVAL;
	}

	/* Handle unaligned access, shouldnt be needed when using the
	 * block device, as strategy handles it, so only low level
	 * accesses will use this path
	 */
	/* XXX^2 */
#if 0
	if (len < chip->nc_page_size)
		panic("TODO page size is larger than read size");
#endif

	if (len % chip->nc_page_size != 0 ||
	    offset % chip->nc_page_size != 0) {
		return nand_flash_read_unaligned(self,
		    offset, len, retlen, buf);
	}

	bufp = buf;
	addr = offset;
	pages = len / chip->nc_page_size;

	mutex_enter(&sc->sc_device_lock);
	for (i = 0; i < pages; i++) {
		/* XXX do we need this check here? */
		if (nand_isbad(self, addr)) {
			aprint_error_dev(self, "bad block encountered\n");
			error = EIO;
			goto out;
		}
		error = nand_read_page(self, addr, bufp);
		if (error)
			goto out;

		bufp += chip->nc_page_size;
		addr += chip->nc_page_size;
		*retlen += chip->nc_page_size;
	}
out:
	mutex_exit(&sc->sc_device_lock);

	return error;
}

int
nand_flash_isbad(device_t self, flash_off_t ofs, bool *is_bad)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	bool result;

	if (ofs > chip->nc_size) {
		DPRINTF(("nand_flash_isbad: offset 0x%jx is larger than"
			" device size (0x%jx)\n", (uintmax_t)ofs,
			(uintmax_t)chip->nc_size));
		return EINVAL;
	}

	if (ofs % chip->nc_block_size != 0) {
		DPRINTF(("offset (0x%jx) is not a multiple of block size "
			"(%ju)",
			(uintmax_t)ofs, (uintmax_t)chip->nc_block_size));
		return EINVAL;
	}

	mutex_enter(&sc->sc_device_lock);
	result = nand_isbad(self, ofs);
	mutex_exit(&sc->sc_device_lock);

	*is_bad = result;

	return 0;
}

int
nand_flash_markbad(device_t self, flash_off_t ofs)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;

	if (ofs > chip->nc_size) {
		DPRINTF(("nand_flash_markbad: offset 0x%jx is larger than"
			" device size (0x%jx)\n", ofs,
			(uintmax_t)chip->nc_size));
		return EINVAL;
	}

	if (ofs % chip->nc_block_size != 0) {
		panic("offset (%ju) is not a multiple of block size (%ju)",
		    (uintmax_t)ofs, (uintmax_t)chip->nc_block_size);
	}

	mutex_enter(&sc->sc_device_lock);
	nand_markbad(self, ofs);
	mutex_exit(&sc->sc_device_lock);

	return 0;
}

int
nand_flash_erase(device_t self,
    struct flash_erase_instruction *ei)
{
	struct nand_softc *sc = device_private(self);
	struct nand_chip *chip = &sc->sc_chip;
	flash_off_t addr;
	int error = 0;

	if (ei->ei_addr < 0 || ei->ei_len < chip->nc_block_size)
		return EINVAL;

	if (ei->ei_addr + ei->ei_len > chip->nc_size) {
		DPRINTF(("nand_flash_erase: erase address is over the end"
			" of the device\n"));
		return EINVAL;
	}

	if (ei->ei_addr % chip->nc_block_size != 0) {
		aprint_error_dev(self,
		    "nand_flash_erase: ei_addr (%ju) is not"
		    " a multiple of block size (%ju)",
		    (uintmax_t)ei->ei_addr,
		    (uintmax_t)chip->nc_block_size);
		return EINVAL;
	}

	if (ei->ei_len % chip->nc_block_size != 0) {
		aprint_error_dev(self,
		    "nand_flash_erase: ei_len (%ju) is not"
		    " a multiple of block size (%ju)",
		    (uintmax_t)ei->ei_len,
		    (uintmax_t)chip->nc_block_size);
		return EINVAL;
	}

	mutex_enter(&sc->sc_device_lock);
	addr = ei->ei_addr;
	while (addr < ei->ei_addr + ei->ei_len) {
		if (nand_isbad(self, addr)) {
			aprint_error_dev(self, "bad block encountered\n");
			ei->ei_state = FLASH_ERASE_FAILED;
			error = EIO;
			goto out;
		}

		error = nand_erase_block(self, addr);
		if (error) {
			ei->ei_state = FLASH_ERASE_FAILED;
			goto out;
		}

		addr += chip->nc_block_size;
	}
	mutex_exit(&sc->sc_device_lock);

	ei->ei_state = FLASH_ERASE_DONE;
	if (ei->ei_callback != NULL) {
		ei->ei_callback(ei);
	}

	return 0;
out:
	mutex_exit(&sc->sc_device_lock);

	return error;
}

MODULE(MODULE_CLASS_DRIVER, nand, "flash");

#ifdef _MODULE
#include "ioconf.c"
#endif

static int
nand_modcmd(modcmd_t cmd, void *opaque)
{
	switch (cmd) {
	case MODULE_CMD_INIT:
#ifdef _MODULE
		return config_init_component(cfdriver_ioconf_nand,
		    cfattach_ioconf_nand, cfdata_ioconf_nand);
#else
		return 0;
#endif
	case MODULE_CMD_FINI:
#ifdef _MODULE
		return config_fini_component(cfdriver_ioconf_nand,
		    cfattach_ioconf_nand, cfdata_ioconf_nand);
#else
		return 0;
#endif
	default:
		return ENOTTY;
	}
}