summaryrefslogtreecommitdiffstats
path: root/uClinux-2.4.20-uc1/drivers/scsi/sd.c
blob: 1e0749b9f0ba7f251d9a2e25f8372a4a4fecd082 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
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
/*
 *      sd.c Copyright (C) 1992 Drew Eckhardt
 *           Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
 *
 *      Linux scsi disk driver
 *              Initial versions: Drew Eckhardt
 *              Subsequent revisions: Eric Youngdale
 *
 *      <drew@colorado.edu>
 *
 *       Modified by Eric Youngdale ericy@andante.org to
 *       add scatter-gather, multiple outstanding request, and other
 *       enhancements.
 *
 *       Modified by Eric Youngdale eric@andante.org to support loadable
 *       low-level scsi drivers.
 *
 *       Modified by Jirka Hanika geo@ff.cuni.cz to support more
 *       scsi disks using eight major numbers.
 *
 *       Modified by Richard Gooch rgooch@atnf.csiro.au to support devfs.
 *	
 *	 Modified by Torben Mathiasen tmm@image.dk
 *       Resource allocation fixes in sd_init and cleanups.
 *	
 *	 Modified by Alex Davis <letmein@erols.com>
 *       Fix problem where partition info not being read in sd_open.
 *	
 *	 Modified by Alex Davis <letmein@erols.com>
 *       Fix problem where removable media could be ejected after sd_open.
 */

#include <linux/config.h>
#include <linux/module.h>

#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/hdreg.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/init.h>

#include <linux/smp.h>

#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/io.h>

#define MAJOR_NR SCSI_DISK0_MAJOR
#include <linux/blk.h>
#include <linux/blkpg.h>
#include "scsi.h"
#include "hosts.h"
#include "sd.h"
#include <scsi/scsi_ioctl.h>
#include "constants.h"
#include <scsi/scsicam.h>	/* must follow "hosts.h" */

#include <linux/genhd.h>

/*
 *  static const char RCSid[] = "$Header:";
 */

/* system major --> sd_gendisks index */
#define SD_MAJOR_IDX(i)		(MAJOR(i) & SD_MAJOR_MASK)
/* sd_gendisks index --> system major */
#define SD_MAJOR(i) (!(i) ? SCSI_DISK0_MAJOR : SCSI_DISK1_MAJOR-1+(i))

#define SD_PARTITION(dev)	((SD_MAJOR_IDX(dev) << 8) | (MINOR(dev) & 255))

#define SCSI_DISKS_PER_MAJOR	16
#define SD_MAJOR_NUMBER(i)	SD_MAJOR((i) >> 8)
#define SD_MINOR_NUMBER(i)	((i) & 255)
#define MKDEV_SD_PARTITION(i)	MKDEV(SD_MAJOR_NUMBER(i), (i) & 255)
#define MKDEV_SD(index)		MKDEV_SD_PARTITION((index) << 4)
#define N_USED_SCSI_DISKS  (sd_template.dev_max + SCSI_DISKS_PER_MAJOR - 1)
#define N_USED_SD_MAJORS   (N_USED_SCSI_DISKS / SCSI_DISKS_PER_MAJOR)

#define MAX_RETRIES 5

/*
 *  Time out in seconds for disks and Magneto-opticals (which are slower).
 */

#define SD_TIMEOUT (30 * HZ)
#define SD_MOD_TIMEOUT (75 * HZ)

static Scsi_Disk *rscsi_disks;
static struct gendisk *sd_gendisks;
static int *sd_sizes;
static int *sd_blocksizes;
static int *sd_hardsizes;	/* Hardware sector size */
static int *sd_max_sectors;

static int check_scsidisk_media_change(kdev_t);
static int fop_revalidate_scsidisk(kdev_t);

static int sd_init_onedisk(int);


static int sd_init(void);
static void sd_finish(void);
static int sd_attach(Scsi_Device *);
static int sd_detect(Scsi_Device *);
static void sd_detach(Scsi_Device *);
static int sd_init_command(Scsi_Cmnd *);

static struct Scsi_Device_Template sd_template = {
	name:"disk",
	tag:"sd",
	scsi_type:TYPE_DISK,
	major:SCSI_DISK0_MAJOR,
        /*
         * Secondary range of majors that this driver handles.
         */
	min_major:SCSI_DISK1_MAJOR,
	max_major:SCSI_DISK7_MAJOR,
	blk:1,
	detect:sd_detect,
	init:sd_init,
	finish:sd_finish,
	attach:sd_attach,
	detach:sd_detach,
	init_command:sd_init_command,
};


static void rw_intr(Scsi_Cmnd * SCpnt);

#if defined(CONFIG_PPC)
/*
 * Moved from arch/ppc/pmac_setup.c.  This is where it really belongs.
 */
kdev_t __init
sd_find_target(void *host, int tgt)
{
    Scsi_Disk *dp;
    int i;
    for (dp = rscsi_disks, i = 0; i < sd_template.dev_max; ++i, ++dp)
        if (dp->device != NULL && dp->device->host == host
            && dp->device->id == tgt)
            return MKDEV_SD(i);
    return 0;
}
#endif

static int sd_ioctl(struct inode * inode, struct file * file, unsigned int cmd, unsigned long arg)
{
	kdev_t dev = inode->i_rdev;
	struct Scsi_Host * host;
	Scsi_Device * SDev;
	int diskinfo[4];
    
	SDev = rscsi_disks[DEVICE_NR(dev)].device;
	if (!SDev)
		return -ENODEV;

	/*
	 * If we are in the middle of error recovery, don't let anyone
	 * else try and use this device.  Also, if error recovery fails, it
	 * may try and take the device offline, in which case all further
	 * access to the device is prohibited.
	 */

	if( !scsi_block_when_processing_errors(SDev) )
	{
		return -ENODEV;
	}

	switch (cmd) 
	{
		case HDIO_GETGEO:   /* Return BIOS disk parameters */
		{
			struct hd_geometry *loc = (struct hd_geometry *) arg;
			if(!loc)
				return -EINVAL;

			host = rscsi_disks[DEVICE_NR(dev)].device->host;
	
			/* default to most commonly used values */
	
		        diskinfo[0] = 0x40;
	        	diskinfo[1] = 0x20;
	        	diskinfo[2] = rscsi_disks[DEVICE_NR(dev)].capacity >> 11;
	
			/* override with calculated, extended default, or driver values */
	
			if(host->hostt->bios_param != NULL)
				host->hostt->bios_param(&rscsi_disks[DEVICE_NR(dev)],
					    dev,
					    &diskinfo[0]);
			else scsicam_bios_param(&rscsi_disks[DEVICE_NR(dev)],
					dev, &diskinfo[0]);

			if (put_user(diskinfo[0], &loc->heads) ||
				put_user(diskinfo[1], &loc->sectors) ||
				put_user(diskinfo[2], &loc->cylinders) ||
				put_user(sd_gendisks[SD_MAJOR_IDX(
				    inode->i_rdev)].part[MINOR(
				    inode->i_rdev)].start_sect, &loc->start))
				return -EFAULT;
			return 0;
		}
		case HDIO_GETGEO_BIG:
		{
			struct hd_big_geometry *loc = (struct hd_big_geometry *) arg;

			if(!loc)
				return -EINVAL;

			host = rscsi_disks[DEVICE_NR(dev)].device->host;

			/* default to most commonly used values */

			diskinfo[0] = 0x40;
			diskinfo[1] = 0x20;
			diskinfo[2] = rscsi_disks[DEVICE_NR(dev)].capacity >> 11;

			/* override with calculated, extended default, or driver values */

			if(host->hostt->bios_param != NULL)
				host->hostt->bios_param(&rscsi_disks[DEVICE_NR(dev)],
					    dev,
					    &diskinfo[0]);
			else scsicam_bios_param(&rscsi_disks[DEVICE_NR(dev)],
					dev, &diskinfo[0]);

			if (put_user(diskinfo[0], &loc->heads) ||
				put_user(diskinfo[1], &loc->sectors) ||
				put_user(diskinfo[2], (unsigned int *) &loc->cylinders) ||
				put_user(sd_gendisks[SD_MAJOR_IDX(
				    inode->i_rdev)].part[MINOR(
				    inode->i_rdev)].start_sect, &loc->start))
				return -EFAULT;
			return 0;
		}
		case BLKGETSIZE:
		case BLKGETSIZE64:
		case BLKROSET:
		case BLKROGET:
		case BLKRASET:
		case BLKRAGET:
		case BLKFLSBUF:
		case BLKSSZGET:
		case BLKPG:
		case BLKELVGET:
		case BLKELVSET:
		case BLKBSZGET:
		case BLKBSZSET:
			return blk_ioctl(inode->i_rdev, cmd, arg);

		case BLKRRPART: /* Re-read partition tables */
		        if (!capable(CAP_SYS_ADMIN))
		                return -EACCES;
			return revalidate_scsidisk(dev, 1);

		default:
			return scsi_ioctl(rscsi_disks[DEVICE_NR(dev)].device , cmd, (void *) arg);
	}
}

static void sd_devname(unsigned int disknum, char *buffer)
{
	if (disknum < 26)
		sprintf(buffer, "sd%c", 'a' + disknum);
	else {
		unsigned int min1;
		unsigned int min2;
		/*
		 * For larger numbers of disks, we need to go to a new
		 * naming scheme.
		 */
		min1 = disknum / 26;
		min2 = disknum % 26;
		sprintf(buffer, "sd%c%c", 'a' + min1 - 1, 'a' + min2);
	}
}

static request_queue_t *sd_find_queue(kdev_t dev)
{
	Scsi_Disk *dpnt;
 	int target;
 	target = DEVICE_NR(dev);

	dpnt = &rscsi_disks[target];
	if (!dpnt->device)
		return NULL;	/* No such device */
	return &dpnt->device->request_queue;
}

static int sd_init_command(Scsi_Cmnd * SCpnt)
{
	int dev, block, this_count;
	struct hd_struct *ppnt;
	Scsi_Disk *dpnt;
#if CONFIG_SCSI_LOGGING
	char nbuff[6];
#endif

	ppnt = &sd_gendisks[SD_MAJOR_IDX(SCpnt->request.rq_dev)].part[MINOR(SCpnt->request.rq_dev)];
	dev = DEVICE_NR(SCpnt->request.rq_dev);

	block = SCpnt->request.sector;
	this_count = SCpnt->request_bufflen >> 9;

	SCSI_LOG_HLQUEUE(1, printk("Doing sd request, dev = 0x%x, block = %d\n",
	    SCpnt->request.rq_dev, block));

	dpnt = &rscsi_disks[dev];
	if (dev >= sd_template.dev_max ||
	    !dpnt->device ||
	    !dpnt->device->online ||
 	    block + SCpnt->request.nr_sectors > ppnt->nr_sects) {
		SCSI_LOG_HLQUEUE(2, printk("Finishing %ld sectors\n", SCpnt->request.nr_sectors));
		SCSI_LOG_HLQUEUE(2, printk("Retry with 0x%p\n", SCpnt));
		return 0;
	}
	block += ppnt->start_sect;
	if (dpnt->device->changed) {
		/*
		 * quietly refuse to do anything to a changed disc until the changed
		 * bit has been reset
		 */
		/* printk("SCSI disk has been changed. Prohibiting further I/O.\n"); */
		return 0;
	}
	SCSI_LOG_HLQUEUE(2, sd_devname(dev, nbuff));
	SCSI_LOG_HLQUEUE(2, printk("%s : real dev = /dev/%d, block = %d\n",
				   nbuff, dev, block));

	/*
	 * If we have a 1K hardware sectorsize, prevent access to single
	 * 512 byte sectors.  In theory we could handle this - in fact
	 * the scsi cdrom driver must be able to handle this because
	 * we typically use 1K blocksizes, and cdroms typically have
	 * 2K hardware sectorsizes.  Of course, things are simpler
	 * with the cdrom, since it is read-only.  For performance
	 * reasons, the filesystems should be able to handle this
	 * and not force the scsi disk driver to use bounce buffers
	 * for this.
	 */
	if (dpnt->device->sector_size == 1024) {
		if ((block & 1) || (SCpnt->request.nr_sectors & 1)) {
			printk("sd.c:Bad block number requested");
			return 0;
		} else {
			block = block >> 1;
			this_count = this_count >> 1;
		}
	}
	if (dpnt->device->sector_size == 2048) {
		if ((block & 3) || (SCpnt->request.nr_sectors & 3)) {
			printk("sd.c:Bad block number requested");
			return 0;
		} else {
			block = block >> 2;
			this_count = this_count >> 2;
		}
	}
	if (dpnt->device->sector_size == 4096) {
		if ((block & 7) || (SCpnt->request.nr_sectors & 7)) {
			printk("sd.c:Bad block number requested");
			return 0;
		} else {
			block = block >> 3;
			this_count = this_count >> 3;
		}
	}
	switch (SCpnt->request.cmd) {
	case WRITE:
		if (!dpnt->device->writeable) {
			return 0;
		}
		SCpnt->cmnd[0] = WRITE_6;
		SCpnt->sc_data_direction = SCSI_DATA_WRITE;
		break;
	case READ:
		SCpnt->cmnd[0] = READ_6;
		SCpnt->sc_data_direction = SCSI_DATA_READ;
		break;
	default:
		panic("Unknown sd command %d\n", SCpnt->request.cmd);
	}

	SCSI_LOG_HLQUEUE(2, printk("%s : %s %d/%ld 512 byte blocks.\n",
				   nbuff,
		   (SCpnt->request.cmd == WRITE) ? "writing" : "reading",
				 this_count, SCpnt->request.nr_sectors));

	SCpnt->cmnd[1] = (SCpnt->device->scsi_level <= SCSI_2) ?
			 ((SCpnt->lun << 5) & 0xe0) : 0;

	if (((this_count > 0xff) || (block > 0x1fffff)) || SCpnt->device->ten) {
		if (this_count > 0xffff)
			this_count = 0xffff;

		SCpnt->cmnd[0] += READ_10 - READ_6;
		SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
		SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
		SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
		SCpnt->cmnd[5] = (unsigned char) block & 0xff;
		SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
		SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
		SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
	} else {
		if (this_count > 0xff)
			this_count = 0xff;

		SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
		SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
		SCpnt->cmnd[3] = (unsigned char) block & 0xff;
		SCpnt->cmnd[4] = (unsigned char) this_count;
		SCpnt->cmnd[5] = 0;
	}

	/*
	 * We shouldn't disconnect in the middle of a sector, so with a dumb
	 * host adapter, it's safe to assume that we can at least transfer
	 * this many bytes between each connect / disconnect.
	 */
	SCpnt->transfersize = dpnt->device->sector_size;
	SCpnt->underflow = this_count << 9;

	SCpnt->allowed = MAX_RETRIES;
	SCpnt->timeout_per_command = (SCpnt->device->type == TYPE_DISK ?
				      SD_TIMEOUT : SD_MOD_TIMEOUT);

	/*
	 * This is the completion routine we use.  This is matched in terms
	 * of capability to this function.
	 */
	SCpnt->done = rw_intr;

	/*
	 * This indicates that the command is ready from our end to be
	 * queued.
	 */
	return 1;
}

static int sd_open(struct inode *inode, struct file *filp)
{
	int target, retval = -ENXIO;
	Scsi_Device * SDev;
	target = DEVICE_NR(inode->i_rdev);

	SCSI_LOG_HLQUEUE(1, printk("target=%d, max=%d\n", target, sd_template.dev_max));

	if (target >= sd_template.dev_max || !rscsi_disks[target].device)
		return -ENXIO;	/* No such device */

	/*
	 * If the device is in error recovery, wait until it is done.
	 * If the device is offline, then disallow any access to it.
	 */
	if (!scsi_block_when_processing_errors(rscsi_disks[target].device)) {
		return -ENXIO;
	}
	/*
	 * Make sure that only one process can do a check_change_disk at one time.
	 * This is also used to lock out further access when the partition table
	 * is being re-read.
	 */

	while (rscsi_disks[target].device->busy) {
		barrier();
		cpu_relax();
	}
	/*
	 * The following code can sleep.
	 * Module unloading must be prevented
	 */
	SDev = rscsi_disks[target].device;
	if (SDev->host->hostt->module)
		__MOD_INC_USE_COUNT(SDev->host->hostt->module);
	if (sd_template.module)
		__MOD_INC_USE_COUNT(sd_template.module);
	SDev->access_count++;

	if (rscsi_disks[target].device->removable) {
		SDev->allow_revalidate = 1;
		check_disk_change(inode->i_rdev);
		SDev->allow_revalidate = 0;

		/*
		 * If the drive is empty, just let the open fail.
		 */
		if ((!rscsi_disks[target].ready) && !(filp->f_flags & O_NDELAY)) {
			retval = -ENOMEDIUM;
			goto error_out;
		}

		/*
		 * Similarly, if the device has the write protect tab set,
		 * have the open fail if the user expects to be able to write
		 * to the thing.
		 */
		if ((rscsi_disks[target].write_prot) && (filp->f_mode & 2)) {
			retval = -EROFS;
			goto error_out;
		}
	}
	/*
	 * It is possible that the disk changing stuff resulted in the device
	 * being taken offline.  If this is the case, report this to the user,
	 * and don't pretend that
	 * the open actually succeeded.
	 */
	if (!SDev->online) {
		goto error_out;
	}
	/*
	 * See if we are requesting a non-existent partition.  Do this
	 * after checking for disk change.
	 */
	if (sd_sizes[SD_PARTITION(inode->i_rdev)] == 0) {
		goto error_out;
	}

	if (SDev->removable)
		if (SDev->access_count==1)
			if (scsi_block_when_processing_errors(SDev))
				scsi_ioctl(SDev, SCSI_IOCTL_DOORLOCK, NULL);

	
	return 0;

error_out:
	SDev->access_count--;
	if (SDev->host->hostt->module)
		__MOD_DEC_USE_COUNT(SDev->host->hostt->module);
	if (sd_template.module)
		__MOD_DEC_USE_COUNT(sd_template.module);
	return retval;	
}

static int sd_release(struct inode *inode, struct file *file)
{
	int target;
	Scsi_Device * SDev;

	target = DEVICE_NR(inode->i_rdev);
	SDev = rscsi_disks[target].device;
	if (!SDev)
		return -ENODEV;

	SDev->access_count--;

	if (SDev->removable) {
		if (!SDev->access_count)
			if (scsi_block_when_processing_errors(SDev))
				scsi_ioctl(SDev, SCSI_IOCTL_DOORUNLOCK, NULL);
	}
	if (SDev->host->hostt->module)
		__MOD_DEC_USE_COUNT(SDev->host->hostt->module);
	if (sd_template.module)
		__MOD_DEC_USE_COUNT(sd_template.module);
	return 0;
}

static struct block_device_operations sd_fops =
{
	owner:			THIS_MODULE,
	open:			sd_open,
	release:		sd_release,
	ioctl:			sd_ioctl,
	check_media_change:	check_scsidisk_media_change,
	revalidate:		fop_revalidate_scsidisk
};

/*
 *    If we need more than one SCSI disk major (i.e. more than
 *      16 SCSI disks), we'll have to kmalloc() more gendisks later.
 */

static struct gendisk sd_gendisk =
{
	major:		SCSI_DISK0_MAJOR,
	major_name:	"sd",
	minor_shift:	4,
	max_p:		1 << 4,
	fops:		&sd_fops,
};

#define SD_GENDISK(i)    sd_gendisks[(i) / SCSI_DISKS_PER_MAJOR]

/*
 * rw_intr is the interrupt routine for the device driver.
 * It will be notified on the end of a SCSI read / write, and
 * will take one of several actions based on success or failure.
 */

static void rw_intr(Scsi_Cmnd * SCpnt)
{
	int result = SCpnt->result;
#if CONFIG_SCSI_LOGGING
	char nbuff[6];
#endif
	int this_count = SCpnt->bufflen >> 9;
	int good_sectors = (result == 0 ? this_count : 0);
	int block_sectors = 1;
	long error_sector;

	SCSI_LOG_HLCOMPLETE(1, sd_devname(DEVICE_NR(SCpnt->request.rq_dev), nbuff));

	SCSI_LOG_HLCOMPLETE(1, printk("%s : rw_intr(%d, %x [%x %x])\n", nbuff,
				      SCpnt->host->host_no,
				      result,
				      SCpnt->sense_buffer[0],
				      SCpnt->sense_buffer[2]));

	/*
	   Handle MEDIUM ERRORs that indicate partial success.  Since this is a
	   relatively rare error condition, no care is taken to avoid
	   unnecessary additional work such as memcpy's that could be avoided.
	 */

	/* An error occurred */
	if (driver_byte(result) != 0 && 	/* An error occured */
	    SCpnt->sense_buffer[0] == 0xF0) {	/* Sense data is valid */
		switch (SCpnt->sense_buffer[2]) {
		case MEDIUM_ERROR:
			error_sector = (SCpnt->sense_buffer[3] << 24) |
			(SCpnt->sense_buffer[4] << 16) |
			(SCpnt->sense_buffer[5] << 8) |
			SCpnt->sense_buffer[6];
			if (SCpnt->request.bh != NULL)
				block_sectors = SCpnt->request.bh->b_size >> 9;
			switch (SCpnt->device->sector_size) {
			case 1024:
				error_sector <<= 1;
				if (block_sectors < 2)
					block_sectors = 2;
				break;
			case 2048:
				error_sector <<= 2;
				if (block_sectors < 4)
					block_sectors = 4;
				break;
			case 4096:
				error_sector <<=3;
				if (block_sectors < 8)
					block_sectors = 8;
				break;
			case 256:
				error_sector >>= 1;
				break;
			default:
				break;
			}
			error_sector -= sd_gendisks[SD_MAJOR_IDX(
				SCpnt->request.rq_dev)].part[MINOR(
				SCpnt->request.rq_dev)].start_sect;
			error_sector &= ~(block_sectors - 1);
			good_sectors = error_sector - SCpnt->request.sector;
			if (good_sectors < 0 || good_sectors >= this_count)
				good_sectors = 0;
			break;

		case RECOVERED_ERROR:
			/*
			 * An error occured, but it recovered.  Inform the
			 * user, but make sure that it's not treated as a
			 * hard error.
			 */
			print_sense("sd", SCpnt);
			result = 0;
			SCpnt->sense_buffer[0] = 0x0;
			good_sectors = this_count;
			break;

		case ILLEGAL_REQUEST:
			if (SCpnt->device->ten == 1) {
				if (SCpnt->cmnd[0] == READ_10 ||
				    SCpnt->cmnd[0] == WRITE_10)
					SCpnt->device->ten = 0;
			}
			break;

		default:
			break;
		}
	}
	/*
	 * This calls the generic completion function, now that we know
	 * how many actual sectors finished, and how many sectors we need
	 * to say have failed.
	 */
	scsi_io_completion(SCpnt, good_sectors, block_sectors);
}
/*
 * requeue_sd_request() is the request handler function for the sd driver.
 * Its function in life is to take block device requests, and translate
 * them to SCSI commands.
 */


static int check_scsidisk_media_change(kdev_t full_dev)
{
	int retval;
	int target;
	int flag = 0;
	Scsi_Device * SDev;

	target = DEVICE_NR(full_dev);
	SDev = rscsi_disks[target].device;

	if (target >= sd_template.dev_max || !SDev) {
		printk("SCSI disk request error: invalid device.\n");
		return 0;
	}
	if (!SDev->removable)
		return 0;

	/*
	 * If the device is offline, don't send any commands - just pretend as
	 * if the command failed.  If the device ever comes back online, we
	 * can deal with it then.  It is only because of unrecoverable errors
	 * that we would ever take a device offline in the first place.
	 */
	if (SDev->online == FALSE) {
		rscsi_disks[target].ready = 0;
		SDev->changed = 1;
		return 1;	/* This will force a flush, if called from
				 * check_disk_change */
	}

	/* Using Start/Stop enables differentiation between drive with
	 * no cartridge loaded - NOT READY, drive with changed cartridge -
	 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
	 * This also handles drives that auto spin down. eg iomega jaz 1GB
	 * as this will spin up the drive.
	 */
	retval = -ENODEV;
	if (scsi_block_when_processing_errors(SDev))
		retval = scsi_ioctl(SDev, SCSI_IOCTL_START_UNIT, NULL);

	if (retval) {		/* Unable to test, unit probably not ready.
				 * This usually means there is no disc in the
				 * drive.  Mark as changed, and we will figure
				 * it out later once the drive is available
				 * again.  */

		rscsi_disks[target].ready = 0;
		SDev->changed = 1;
		return 1;	/* This will force a flush, if called from
				 * check_disk_change */
	}
	/*
	 * for removable scsi disk ( FLOPTICAL ) we have to recognise the
	 * presence of disk in the drive. This is kept in the Scsi_Disk
	 * struct and tested at open !  Daniel Roche ( dan@lectra.fr )
	 */

	rscsi_disks[target].ready = 1;	/* FLOPTICAL */

	retval = SDev->changed;
	if (!flag)
		SDev->changed = 0;
	return retval;
}

static int sd_init_onedisk(int i)
{
	unsigned char cmd[10];
	char nbuff[6];
	unsigned char *buffer;
	unsigned long spintime_value = 0;
	int the_result, retries, spintime;
	int sector_size;
	Scsi_Request *SRpnt;

	/*
	 * Get the name of the disk, in case we need to log it somewhere.
	 */
	sd_devname(i, nbuff);

	/*
	 * If the device is offline, don't try and read capacity or any
	 * of the other niceties.
	 */
	if (rscsi_disks[i].device->online == FALSE)
		return i;

	/*
	 * We need to retry the READ_CAPACITY because a UNIT_ATTENTION is
	 * considered a fatal error, and many devices report such an error
	 * just after a scsi bus reset.
	 */

	SRpnt = scsi_allocate_request(rscsi_disks[i].device);
	if (!SRpnt) {
		printk(KERN_WARNING "(sd_init_onedisk:) Request allocation failure.\n");
		return i;
	}

	buffer = (unsigned char *) scsi_malloc(512);
	if (!buffer) {
		printk(KERN_WARNING "(sd_init_onedisk:) Memory allocation failure.\n");
		scsi_release_request(SRpnt);
		return i;
	}

	spintime = 0;

	/* Spin up drives, as required.  Only do this at boot time */
	/* Spinup needs to be done for module loads too. */
	do {
		retries = 0;

		while (retries < 3) {
			cmd[0] = TEST_UNIT_READY;
			cmd[1] = (rscsi_disks[i].device->scsi_level <= SCSI_2) ?
				 ((rscsi_disks[i].device->lun << 5) & 0xe0) : 0;
			memset((void *) &cmd[2], 0, 8);
			SRpnt->sr_cmd_len = 0;
			SRpnt->sr_sense_buffer[0] = 0;
			SRpnt->sr_sense_buffer[2] = 0;
			SRpnt->sr_data_direction = SCSI_DATA_NONE;

			scsi_wait_req (SRpnt, (void *) cmd, (void *) buffer,
				0/*512*/, SD_TIMEOUT, MAX_RETRIES);

			the_result = SRpnt->sr_result;
			retries++;
			if (the_result == 0
			    || SRpnt->sr_sense_buffer[2] != UNIT_ATTENTION)
				break;
		}

		/*
		 * If the drive has indicated to us that it doesn't have
		 * any media in it, don't bother with any of the rest of
		 * this crap.
		 */
		if( the_result != 0
		    && ((driver_byte(the_result) & DRIVER_SENSE) != 0)
		    && SRpnt->sr_sense_buffer[2] == UNIT_ATTENTION
		    && SRpnt->sr_sense_buffer[12] == 0x3A ) {
			rscsi_disks[i].capacity = 0x1fffff;
			sector_size = 512;
			rscsi_disks[i].device->changed = 1;
			rscsi_disks[i].ready = 0;
			break;
		}

		/* Look for non-removable devices that return NOT_READY.
		 * Issue command to spin up drive for these cases. */
		if (the_result && !rscsi_disks[i].device->removable &&
		    SRpnt->sr_sense_buffer[2] == NOT_READY) {
			unsigned long time1;
			if (!spintime) {
				printk("%s: Spinning up disk...", nbuff);
				cmd[0] = START_STOP;
				cmd[1] = (rscsi_disks[i].device->scsi_level <= SCSI_2) ?
				 	 ((rscsi_disks[i].device->lun << 5) & 0xe0) : 0;
				cmd[1] |= 1;	/* Return immediately */
				memset((void *) &cmd[2], 0, 8);
				cmd[4] = 1;	/* Start spin cycle */
				SRpnt->sr_cmd_len = 0;
				SRpnt->sr_sense_buffer[0] = 0;
				SRpnt->sr_sense_buffer[2] = 0;

				SRpnt->sr_data_direction = SCSI_DATA_READ;
				scsi_wait_req(SRpnt, (void *) cmd, (void *) buffer,
					    0/*512*/, SD_TIMEOUT, MAX_RETRIES);
				spintime_value = jiffies;
			}
			spintime = 1;
			time1 = HZ;
			/* Wait 1 second for next try */
			do {
				current->state = TASK_UNINTERRUPTIBLE;
				time1 = schedule_timeout(time1);
			} while(time1);
			printk(".");
		}
	} while (the_result && spintime &&
		 time_after(spintime_value + 100 * HZ, jiffies));
	if (spintime) {
		if (the_result)
			printk("not responding...\n");
		else
			printk("ready\n");
	}
	retries = 3;
	do {
		cmd[0] = READ_CAPACITY;
		cmd[1] = (rscsi_disks[i].device->scsi_level <= SCSI_2) ?
			 ((rscsi_disks[i].device->lun << 5) & 0xe0) : 0;
		memset((void *) &cmd[2], 0, 8);
		memset((void *) buffer, 0, 8);
		SRpnt->sr_cmd_len = 0;
		SRpnt->sr_sense_buffer[0] = 0;
		SRpnt->sr_sense_buffer[2] = 0;

		SRpnt->sr_data_direction = SCSI_DATA_READ;
		scsi_wait_req(SRpnt, (void *) cmd, (void *) buffer,
			    8, SD_TIMEOUT, MAX_RETRIES);

		the_result = SRpnt->sr_result;
		retries--;

	} while (the_result && retries);

	/*
	 * The SCSI standard says:
	 * "READ CAPACITY is necessary for self configuring software"
	 *  While not mandatory, support of READ CAPACITY is strongly
	 *  encouraged.
	 *  We used to die if we couldn't successfully do a READ CAPACITY.
	 *  But, now we go on about our way.  The side effects of this are
	 *
	 *  1. We can't know block size with certainty. I have said
	 *     "512 bytes is it" as this is most common.
	 *
	 *  2. Recovery from when someone attempts to read past the
	 *     end of the raw device will be slower.
	 */

	if (the_result) {
		printk("%s : READ CAPACITY failed.\n"
		       "%s : status = %x, message = %02x, host = %d, driver = %02x \n",
		       nbuff, nbuff,
		       status_byte(the_result),
		       msg_byte(the_result),
		       host_byte(the_result),
		       driver_byte(the_result)
		    );
		if (driver_byte(the_result) & DRIVER_SENSE)
			print_req_sense("sd", SRpnt);
		else
			printk("%s : sense not available. \n", nbuff);

		printk("%s : block size assumed to be 512 bytes, disk size 1GB.  \n",
		       nbuff);
		rscsi_disks[i].capacity = 0x1fffff;
		sector_size = 512;

		/* Set dirty bit for removable devices if not ready -
		 * sometimes drives will not report this properly. */
		if (rscsi_disks[i].device->removable &&
		    SRpnt->sr_sense_buffer[2] == NOT_READY)
			rscsi_disks[i].device->changed = 1;

	} else {
		/*
		 * FLOPTICAL, if read_capa is ok, drive is assumed to be ready
		 */
		rscsi_disks[i].ready = 1;

		rscsi_disks[i].capacity = 1 + ((buffer[0] << 24) |
					       (buffer[1] << 16) |
					       (buffer[2] << 8) |
					       buffer[3]);

		sector_size = (buffer[4] << 24) |
		    (buffer[5] << 16) | (buffer[6] << 8) | buffer[7];

		if (sector_size == 0) {
			sector_size = 512;
			printk("%s : sector size 0 reported, assuming 512.\n",
			       nbuff);
		}
		if (sector_size != 512 &&
		    sector_size != 1024 &&
		    sector_size != 2048 &&
		    sector_size != 4096 &&
		    sector_size != 256) {
			printk("%s : unsupported sector size %d.\n",
			       nbuff, sector_size);
			/*
			 * The user might want to re-format the drive with
			 * a supported sectorsize.  Once this happens, it
			 * would be relatively trivial to set the thing up.
			 * For this reason, we leave the thing in the table.
			 */
			rscsi_disks[i].capacity = 0;
		}
		if (sector_size > 1024) {
			int m;

			/*
			 * We must fix the sd_blocksizes and sd_hardsizes
			 * to allow us to read the partition tables.
			 * The disk reading code does not allow for reading
			 * of partial sectors.
			 */
			for (m = i << 4; m < ((i + 1) << 4); m++) {
				sd_blocksizes[m] = sector_size;
			}
		} {
			/*
			 * The msdos fs needs to know the hardware sector size
			 * So I have created this table. See ll_rw_blk.c
			 * Jacques Gelinas (Jacques@solucorp.qc.ca)
			 */
			int m;
			int hard_sector = sector_size;
			int sz = rscsi_disks[i].capacity * (hard_sector/256);

			/* There are 16 minors allocated for each major device */
			for (m = i << 4; m < ((i + 1) << 4); m++) {
				sd_hardsizes[m] = hard_sector;
			}

			printk("SCSI device %s: "
			       "%d %d-byte hdwr sectors (%d MB)\n",
			       nbuff, rscsi_disks[i].capacity,
			       hard_sector, (sz/2 - sz/1250 + 974)/1950);
		}

		/* Rescale capacity to 512-byte units */
		if (sector_size == 4096)
			rscsi_disks[i].capacity <<= 3;
		if (sector_size == 2048)
			rscsi_disks[i].capacity <<= 2;
		if (sector_size == 1024)
			rscsi_disks[i].capacity <<= 1;
		if (sector_size == 256)
			rscsi_disks[i].capacity >>= 1;
	}


	/*
	 * Unless otherwise specified, this is not write protected.
	 */
	rscsi_disks[i].write_prot = 0;
	if (rscsi_disks[i].device->removable && rscsi_disks[i].ready) {
		/* FLOPTICAL */

		/*
		 * For removable scsi disk ( FLOPTICAL ) we have to recognise
		 * the Write Protect Flag. This flag is kept in the Scsi_Disk
		 * struct and tested at open !
		 * Daniel Roche ( dan@lectra.fr )
		 *
		 * Changed to get all pages (0x3f) rather than page 1 to
		 * get around devices which do not have a page 1.  Since
		 * we're only interested in the header anyway, this should
		 * be fine.
		 *   -- Matthew Dharm (mdharm-scsi@one-eyed-alien.net)
		 */

		memset((void *) &cmd[0], 0, 8);
		cmd[0] = MODE_SENSE;
		cmd[1] = (rscsi_disks[i].device->scsi_level <= SCSI_2) ?
			 ((rscsi_disks[i].device->lun << 5) & 0xe0) : 0;
		cmd[2] = 0x3f;	/* Get all pages */
		cmd[4] = 255;   /* Ask for 255 bytes, even tho we want just the first 8 */
		SRpnt->sr_cmd_len = 0;
		SRpnt->sr_sense_buffer[0] = 0;
		SRpnt->sr_sense_buffer[2] = 0;

		/* same code as READCAPA !! */
		SRpnt->sr_data_direction = SCSI_DATA_READ;
		scsi_wait_req(SRpnt, (void *) cmd, (void *) buffer,
			    512, SD_TIMEOUT, MAX_RETRIES);

		the_result = SRpnt->sr_result;

		if (the_result) {
			printk("%s: test WP failed, assume Write Enabled\n", nbuff);
		} else {
			rscsi_disks[i].write_prot = ((buffer[2] & 0x80) != 0);
			printk("%s: Write Protect is %s\n", nbuff,
			       rscsi_disks[i].write_prot ? "on" : "off");
		}

	}			/* check for write protect */
	SRpnt->sr_device->ten = 1;
	SRpnt->sr_device->remap = 1;
	SRpnt->sr_device->sector_size = sector_size;
	/* Wake up a process waiting for device */
	scsi_release_request(SRpnt);
	SRpnt = NULL;

	scsi_free(buffer, 512);
	return i;
}

/*
 * The sd_init() function looks at all SCSI drives present, determines
 * their size, and reads partition table entries for them.
 */

static int sd_registered;

static int sd_init()
{
	int i;

	if (sd_template.dev_noticed == 0)
		return 0;

	if (!rscsi_disks)
		sd_template.dev_max = sd_template.dev_noticed + SD_EXTRA_DEVS;

	if (sd_template.dev_max > N_SD_MAJORS * SCSI_DISKS_PER_MAJOR)
		sd_template.dev_max = N_SD_MAJORS * SCSI_DISKS_PER_MAJOR;

	if (!sd_registered) {
		for (i = 0; i < N_USED_SD_MAJORS; i++) {
			if (devfs_register_blkdev(SD_MAJOR(i), "sd", &sd_fops)) {
				printk("Unable to get major %d for SCSI disk\n", SD_MAJOR(i));
				sd_template.dev_noticed = 0;
				return 1;
			}
		}
		sd_registered++;
	}
	/* We do not support attaching loadable devices yet. */
	if (rscsi_disks)
		return 0;

	rscsi_disks = kmalloc(sd_template.dev_max * sizeof(Scsi_Disk), GFP_ATOMIC);
	if (!rscsi_disks)
		goto cleanup_devfs;
	memset(rscsi_disks, 0, sd_template.dev_max * sizeof(Scsi_Disk));

	/* for every (necessary) major: */
	sd_sizes = kmalloc((sd_template.dev_max << 4) * sizeof(int), GFP_ATOMIC);
	if (!sd_sizes)
		goto cleanup_disks;
	memset(sd_sizes, 0, (sd_template.dev_max << 4) * sizeof(int));

	sd_blocksizes = kmalloc((sd_template.dev_max << 4) * sizeof(int), GFP_ATOMIC);
	if (!sd_blocksizes)
		goto cleanup_sizes;
	
	sd_hardsizes = kmalloc((sd_template.dev_max << 4) * sizeof(int), GFP_ATOMIC);
	if (!sd_hardsizes)
		goto cleanup_blocksizes;

	sd_max_sectors = kmalloc((sd_template.dev_max << 4) * sizeof(int), GFP_ATOMIC);
	if (!sd_max_sectors)
		goto cleanup_max_sectors;

	for (i = 0; i < sd_template.dev_max << 4; i++) {
		sd_blocksizes[i] = 1024;
		sd_hardsizes[i] = 512;
		/*
		 * Allow lowlevel device drivers to generate 512k large scsi
		 * commands if they know what they're doing and they ask for it
		 * explicitly via the SHpnt->max_sectors API.
		 */
		sd_max_sectors[i] = MAX_SEGMENTS*8;
	}

	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		blksize_size[SD_MAJOR(i)] = sd_blocksizes + i * (SCSI_DISKS_PER_MAJOR << 4);
		hardsect_size[SD_MAJOR(i)] = sd_hardsizes + i * (SCSI_DISKS_PER_MAJOR << 4);
		max_sectors[SD_MAJOR(i)] = sd_max_sectors + i * (SCSI_DISKS_PER_MAJOR << 4);
	}

	sd_gendisks = kmalloc(N_USED_SD_MAJORS * sizeof(struct gendisk), GFP_ATOMIC);
	if (!sd_gendisks)
		goto cleanup_sd_gendisks;
	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		sd_gendisks[i] = sd_gendisk;	/* memcpy */
		sd_gendisks[i].de_arr = kmalloc (SCSI_DISKS_PER_MAJOR * sizeof *sd_gendisks[i].de_arr,
                                                 GFP_ATOMIC);
		if (!sd_gendisks[i].de_arr)
			goto cleanup_gendisks_de_arr;
                memset (sd_gendisks[i].de_arr, 0,
                        SCSI_DISKS_PER_MAJOR * sizeof *sd_gendisks[i].de_arr);
		sd_gendisks[i].flags = kmalloc (SCSI_DISKS_PER_MAJOR * sizeof *sd_gendisks[i].flags,
                                                GFP_ATOMIC);
		if (!sd_gendisks[i].flags)
			goto cleanup_gendisks_flags;
                memset (sd_gendisks[i].flags, 0,
                        SCSI_DISKS_PER_MAJOR * sizeof *sd_gendisks[i].flags);
		sd_gendisks[i].major = SD_MAJOR(i);
		sd_gendisks[i].major_name = "sd";
		sd_gendisks[i].minor_shift = 4;
		sd_gendisks[i].max_p = 1 << 4;
		sd_gendisks[i].part = kmalloc((SCSI_DISKS_PER_MAJOR << 4) * sizeof(struct hd_struct),
						GFP_ATOMIC);
		if (!sd_gendisks[i].part)
			goto cleanup_gendisks_part;
		memset(sd_gendisks[i].part, 0, (SCSI_DISKS_PER_MAJOR << 4) * sizeof(struct hd_struct));
		sd_gendisks[i].sizes = sd_sizes + (i * SCSI_DISKS_PER_MAJOR << 4);
		sd_gendisks[i].nr_real = 0;
		sd_gendisks[i].real_devices =
		    (void *) (rscsi_disks + i * SCSI_DISKS_PER_MAJOR);
	}

	return 0;

cleanup_gendisks_part:
	kfree(sd_gendisks[i].flags);
cleanup_gendisks_flags:
	kfree(sd_gendisks[i].de_arr);
cleanup_gendisks_de_arr:
	while (--i >= 0 ) {
		kfree(sd_gendisks[i].de_arr);
		kfree(sd_gendisks[i].flags);
		kfree(sd_gendisks[i].part);
	}
	kfree(sd_gendisks);
	sd_gendisks = NULL;
cleanup_sd_gendisks:
	kfree(sd_max_sectors);
cleanup_max_sectors:
	kfree(sd_hardsizes);
cleanup_blocksizes:
	kfree(sd_blocksizes);
cleanup_sizes:
	kfree(sd_sizes);
cleanup_disks:
	kfree(rscsi_disks);
	rscsi_disks = NULL;
cleanup_devfs:
	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		devfs_unregister_blkdev(SD_MAJOR(i), "sd");
	}
	sd_registered--;
	sd_template.dev_noticed = 0;
	return 1;
}


static void sd_finish()
{
	int i;

	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		blk_dev[SD_MAJOR(i)].queue = sd_find_queue;
		add_gendisk(&sd_gendisks[i]);
	}

	for (i = 0; i < sd_template.dev_max; ++i)
		if (!rscsi_disks[i].capacity && rscsi_disks[i].device) {
			sd_init_onedisk(i);
			if (!rscsi_disks[i].has_part_table) {
				sd_sizes[i << 4] = rscsi_disks[i].capacity;
				register_disk(&SD_GENDISK(i), MKDEV_SD(i),
						1<<4, &sd_fops,
						rscsi_disks[i].capacity);
				rscsi_disks[i].has_part_table = 1;
			}
		}
	/* If our host adapter is capable of scatter-gather, then we increase
	 * the read-ahead to 60 blocks (120 sectors).  If not, we use
	 * a two block (4 sector) read ahead. We can only respect this with the
	 * granularity of every 16 disks (one device major).
	 */
	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		read_ahead[SD_MAJOR(i)] =
		    (rscsi_disks[i * SCSI_DISKS_PER_MAJOR].device
		     && rscsi_disks[i * SCSI_DISKS_PER_MAJOR].device->host->sg_tablesize)
		    ? 120	/* 120 sector read-ahead */
		    : 4;	/* 4 sector read-ahead */
	}

	return;
}

static int sd_detect(Scsi_Device * SDp)
{
	if (SDp->type != TYPE_DISK && SDp->type != TYPE_MOD)
		return 0;
	sd_template.dev_noticed++;
	return 1;
}

static int sd_attach(Scsi_Device * SDp)
{
        unsigned int devnum;
	Scsi_Disk *dpnt;
	int i;
	char nbuff[6];

	if (SDp->type != TYPE_DISK && SDp->type != TYPE_MOD)
		return 0;

	if (sd_template.nr_dev >= sd_template.dev_max || rscsi_disks == NULL) {
		SDp->attached--;
		return 1;
	}
	for (dpnt = rscsi_disks, i = 0; i < sd_template.dev_max; i++, dpnt++)
		if (!dpnt->device)
			break;

	if (i >= sd_template.dev_max) {
		printk(KERN_WARNING "scsi_devices corrupt (sd),"
		    " nr_dev %d dev_max %d\n",
		    sd_template.nr_dev, sd_template.dev_max);
		SDp->attached--;
		return 1;
	}

	rscsi_disks[i].device = SDp;
	rscsi_disks[i].has_part_table = 0;
	sd_template.nr_dev++;
	SD_GENDISK(i).nr_real++;
        devnum = i % SCSI_DISKS_PER_MAJOR;
        SD_GENDISK(i).de_arr[devnum] = SDp->de;
        if (SDp->removable)
		SD_GENDISK(i).flags[devnum] |= GENHD_FL_REMOVABLE;
	sd_devname(i, nbuff);
	printk("Attached scsi %sdisk %s at scsi%d, channel %d, id %d, lun %d\n",
	       SDp->removable ? "removable " : "",
	       nbuff, SDp->host->host_no, SDp->channel, SDp->id, SDp->lun);
	return 0;
}

#define DEVICE_BUSY rscsi_disks[target].device->busy
#define ALLOW_REVALIDATE rscsi_disks[target].device->allow_revalidate
#define USAGE rscsi_disks[target].device->access_count
#define CAPACITY rscsi_disks[target].capacity
#define MAYBE_REINIT  sd_init_onedisk(target)

/* This routine is called to flush all partitions and partition tables
 * for a changed scsi disk, and then re-read the new partition table.
 * If we are revalidating a disk because of a media change, then we
 * enter with usage == 0.  If we are using an ioctl, we automatically have
 * usage == 1 (we need an open channel to use an ioctl :-), so this
 * is our limit.
 */
int revalidate_scsidisk(kdev_t dev, int maxusage)
{
	struct gendisk *sdgd;
	int target;
	int max_p;
	int start;
	int i;

	target = DEVICE_NR(dev);

	if (DEVICE_BUSY || (ALLOW_REVALIDATE == 0 && USAGE > maxusage)) {
		printk("Device busy for revalidation (usage=%d)\n", USAGE);
		return -EBUSY;
	}
	DEVICE_BUSY = 1;

	sdgd = &SD_GENDISK(target);
	max_p = sd_gendisk.max_p;
	start = target << sd_gendisk.minor_shift;

	for (i = max_p - 1; i >= 0; i--) {
		int index = start + i;
		invalidate_device(MKDEV_SD_PARTITION(index), 1);
		sdgd->part[SD_MINOR_NUMBER(index)].start_sect = 0;
		sdgd->part[SD_MINOR_NUMBER(index)].nr_sects = 0;
		/*
		 * Reset the blocksize for everything so that we can read
		 * the partition table.  Technically we will determine the
		 * correct block size when we revalidate, but we do this just
		 * to make sure that everything remains consistent.
		 */
		sd_blocksizes[index] = 1024;
		if (rscsi_disks[target].device->sector_size == 2048)
			sd_blocksizes[index] = 2048;
		else
			sd_blocksizes[index] = 1024;
	}

#ifdef MAYBE_REINIT
	MAYBE_REINIT;
#endif

	grok_partitions(&SD_GENDISK(target), target % SCSI_DISKS_PER_MAJOR,
			1<<4, CAPACITY);

	DEVICE_BUSY = 0;
	return 0;
}

static int fop_revalidate_scsidisk(kdev_t dev)
{
	return revalidate_scsidisk(dev, 0);
}
static void sd_detach(Scsi_Device * SDp)
{
	Scsi_Disk *dpnt;
	struct gendisk *sdgd;
	int i, j;
	int max_p;
	int start;

	if (rscsi_disks == NULL)
		return;

	for (dpnt = rscsi_disks, i = 0; i < sd_template.dev_max; i++, dpnt++)
		if (dpnt->device == SDp) {

			/* If we are disconnecting a disk driver, sync and invalidate
			 * everything */
			sdgd = &SD_GENDISK(i);
			max_p = sd_gendisk.max_p;
			start = i << sd_gendisk.minor_shift;

			for (j = max_p - 1; j >= 0; j--) {
				int index = start + j;
				invalidate_device(MKDEV_SD_PARTITION(index), 1);
				sdgd->part[SD_MINOR_NUMBER(index)].start_sect = 0;
				sdgd->part[SD_MINOR_NUMBER(index)].nr_sects = 0;
				sd_sizes[index] = 0;
			}
                        devfs_register_partitions (sdgd,
                                                   SD_MINOR_NUMBER (start), 1);
			/* unregister_disk() */
			dpnt->has_part_table = 0;
			dpnt->device = NULL;
			dpnt->capacity = 0;
			SDp->attached--;
			sd_template.dev_noticed--;
			sd_template.nr_dev--;
			SD_GENDISK(i).nr_real--;
			return;
		}
	return;
}

static int __init init_sd(void)
{
	sd_template.module = THIS_MODULE;
	return scsi_register_module(MODULE_SCSI_DEV, &sd_template);
}

static void __exit exit_sd(void)
{
	int i;

	scsi_unregister_module(MODULE_SCSI_DEV, &sd_template);

	for (i = 0; i < N_USED_SD_MAJORS; i++)
		devfs_unregister_blkdev(SD_MAJOR(i), "sd");

	sd_registered--;
	if (rscsi_disks != NULL) {
		kfree(rscsi_disks);
		kfree(sd_sizes);
		kfree(sd_blocksizes);
		kfree(sd_hardsizes);
		for (i = 0; i < N_USED_SD_MAJORS; i++) {
#if 0 /* XXX aren't we forgetting to deallocate something? */
			kfree(sd_gendisks[i].de_arr);
			kfree(sd_gendisks[i].flags);
#endif
			kfree(sd_gendisks[i].part);
		}
	}
	for (i = 0; i < N_USED_SD_MAJORS; i++) {
		del_gendisk(&sd_gendisks[i]);
		blk_size[SD_MAJOR(i)] = NULL;	/* XXX blksize_size actually? */
		hardsect_size[SD_MAJOR(i)] = NULL;
		read_ahead[SD_MAJOR(i)] = 0;
	}
	sd_template.dev_max = 0;
	if (sd_gendisks != NULL)    /* kfree tests for 0, but leave explicit */
		kfree(sd_gendisks);
}

module_init(init_sd);
module_exit(exit_sd);
MODULE_LICENSE("GPL");