xref: /linux/drivers/scsi/scsi_scan.c (revision 8c292e89bd831c8a13e92f3429ef66bbe0b83677)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * scsi_scan.c
4  *
5  * Copyright (C) 2000 Eric Youngdale,
6  * Copyright (C) 2002 Patrick Mansfield
7  *
8  * The general scanning/probing algorithm is as follows, exceptions are
9  * made to it depending on device specific flags, compilation options, and
10  * global variable (boot or module load time) settings.
11  *
12  * A specific LUN is scanned via an INQUIRY command; if the LUN has a
13  * device attached, a scsi_device is allocated and setup for it.
14  *
15  * For every id of every channel on the given host:
16  *
17  * 	Scan LUN 0; if the target responds to LUN 0 (even if there is no
18  * 	device or storage attached to LUN 0):
19  *
20  * 		If LUN 0 has a device attached, allocate and setup a
21  * 		scsi_device for it.
22  *
23  * 		If target is SCSI-3 or up, issue a REPORT LUN, and scan
24  * 		all of the LUNs returned by the REPORT LUN; else,
25  * 		sequentially scan LUNs up until some maximum is reached,
26  * 		or a LUN is seen that cannot have a device attached to it.
27  */
28 
29 #include <linux/module.h>
30 #include <linux/moduleparam.h>
31 #include <linux/init.h>
32 #include <linux/blkdev.h>
33 #include <linux/delay.h>
34 #include <linux/kthread.h>
35 #include <linux/spinlock.h>
36 #include <linux/async.h>
37 #include <linux/slab.h>
38 #include <linux/unaligned.h>
39 
40 #include <scsi/scsi.h>
41 #include <scsi/scsi_cmnd.h>
42 #include <scsi/scsi_device.h>
43 #include <scsi/scsi_driver.h>
44 #include <scsi/scsi_devinfo.h>
45 #include <scsi/scsi_host.h>
46 #include <scsi/scsi_transport.h>
47 #include <scsi/scsi_dh.h>
48 #include <scsi/scsi_eh.h>
49 
50 #include "scsi_priv.h"
51 #include "scsi_logging.h"
52 
53 #define ALLOC_FAILURE_MSG	KERN_ERR "%s: Allocation failure during" \
54 	" SCSI scanning, some SCSI devices might not be configured\n"
55 
56 /*
57  * Default timeout
58  */
59 #define SCSI_TIMEOUT (2*HZ)
60 #define SCSI_REPORT_LUNS_TIMEOUT (30*HZ)
61 
62 /*
63  * Prefix values for the SCSI id's (stored in sysfs name field)
64  */
65 #define SCSI_UID_SER_NUM 'S'
66 #define SCSI_UID_UNKNOWN 'Z'
67 
68 /*
69  * Return values of some of the scanning functions.
70  *
71  * SCSI_SCAN_NO_RESPONSE: no valid response received from the target, this
72  * includes allocation or general failures preventing IO from being sent.
73  *
74  * SCSI_SCAN_TARGET_PRESENT: target responded, but no device is available
75  * on the given LUN.
76  *
77  * SCSI_SCAN_LUN_PRESENT: target responded, and a device is available on a
78  * given LUN.
79  */
80 #define SCSI_SCAN_NO_RESPONSE		0
81 #define SCSI_SCAN_TARGET_PRESENT	1
82 #define SCSI_SCAN_LUN_PRESENT		2
83 
84 static const char *scsi_null_device_strs = "nullnullnullnull";
85 
86 #define MAX_SCSI_LUNS	512
87 
88 static u64 max_scsi_luns = MAX_SCSI_LUNS;
89 
90 module_param_named(max_luns, max_scsi_luns, ullong, S_IRUGO|S_IWUSR);
91 MODULE_PARM_DESC(max_luns,
92 		 "last scsi LUN (should be between 1 and 2^64-1)");
93 
94 #ifdef CONFIG_SCSI_SCAN_ASYNC
95 #define SCSI_SCAN_TYPE_DEFAULT "async"
96 #else
97 #define SCSI_SCAN_TYPE_DEFAULT "sync"
98 #endif
99 
100 static char scsi_scan_type[7] = SCSI_SCAN_TYPE_DEFAULT;
101 
102 module_param_string(scan, scsi_scan_type, sizeof(scsi_scan_type),
103 		    S_IRUGO|S_IWUSR);
104 MODULE_PARM_DESC(scan, "sync, async, manual, or none. "
105 		 "Setting to 'manual' disables automatic scanning, but allows "
106 		 "for manual device scan via the 'scan' sysfs attribute.");
107 
108 static unsigned int scsi_inq_timeout = SCSI_TIMEOUT/HZ + 18;
109 
110 module_param_named(inq_timeout, scsi_inq_timeout, uint, S_IRUGO|S_IWUSR);
111 MODULE_PARM_DESC(inq_timeout,
112 		 "Timeout (in seconds) waiting for devices to answer INQUIRY."
113 		 " Default is 20. Some devices may need more; most need less.");
114 
115 /* This lock protects only this list */
116 static DEFINE_SPINLOCK(async_scan_lock);
117 static LIST_HEAD(scanning_hosts);
118 
119 struct async_scan_data {
120 	struct list_head list;
121 	struct Scsi_Host *shost;
122 	struct completion prev_finished;
123 };
124 
125 /*
126  * scsi_enable_async_suspend - Enable async suspend and resume
127  */
128 void scsi_enable_async_suspend(struct device *dev)
129 {
130 	/*
131 	 * If a user has disabled async probing a likely reason is due to a
132 	 * storage enclosure that does not inject staggered spin-ups. For
133 	 * safety, make resume synchronous as well in that case.
134 	 */
135 	if (strncmp(scsi_scan_type, "async", 5) != 0)
136 		return;
137 	/* Enable asynchronous suspend and resume. */
138 	device_enable_async_suspend(dev);
139 }
140 
141 /**
142  * scsi_complete_async_scans - Wait for asynchronous scans to complete
143  *
144  * When this function returns, any host which started scanning before
145  * this function was called will have finished its scan.  Hosts which
146  * started scanning after this function was called may or may not have
147  * finished.
148  */
149 int scsi_complete_async_scans(void)
150 {
151 	struct async_scan_data *data;
152 
153 	do {
154 		scoped_guard(spinlock, &async_scan_lock)
155 			if (list_empty(&scanning_hosts))
156 				return 0;
157 		/* If we can't get memory immediately, that's OK.  Just
158 		 * sleep a little.  Even if we never get memory, the async
159 		 * scans will finish eventually.
160 		 */
161 		data = kmalloc(sizeof(*data), GFP_KERNEL);
162 		if (!data)
163 			msleep(1);
164 	} while (!data);
165 
166 	data->shost = NULL;
167 	init_completion(&data->prev_finished);
168 
169 	spin_lock(&async_scan_lock);
170 	/* Check that there's still somebody else on the list */
171 	if (list_empty(&scanning_hosts))
172 		goto done;
173 	list_add_tail(&data->list, &scanning_hosts);
174 	spin_unlock(&async_scan_lock);
175 
176 	printk(KERN_INFO "scsi: waiting for bus probes to complete ...\n");
177 	wait_for_completion(&data->prev_finished);
178 
179 	spin_lock(&async_scan_lock);
180 	list_del(&data->list);
181 	if (!list_empty(&scanning_hosts)) {
182 		struct async_scan_data *next = list_entry(scanning_hosts.next,
183 				struct async_scan_data, list);
184 		complete(&next->prev_finished);
185 	}
186  done:
187 	spin_unlock(&async_scan_lock);
188 
189 	kfree(data);
190 	return 0;
191 }
192 
193 /**
194  * scsi_unlock_floptical - unlock device via a special MODE SENSE command
195  * @sdev:	scsi device to send command to
196  * @result:	area to store the result of the MODE SENSE
197  *
198  * Description:
199  *     Send a vendor specific MODE SENSE (not a MODE SELECT) command.
200  *     Called for BLIST_KEY devices.
201  **/
202 static void scsi_unlock_floptical(struct scsi_device *sdev,
203 				  unsigned char *result)
204 {
205 	unsigned char scsi_cmd[MAX_COMMAND_SIZE];
206 
207 	sdev_printk(KERN_NOTICE, sdev, "unlocking floptical drive\n");
208 	scsi_cmd[0] = MODE_SENSE;
209 	scsi_cmd[1] = 0;
210 	scsi_cmd[2] = 0x2e;
211 	scsi_cmd[3] = 0;
212 	scsi_cmd[4] = 0x2a;     /* size */
213 	scsi_cmd[5] = 0;
214 	scsi_execute_cmd(sdev, scsi_cmd, REQ_OP_DRV_IN, result, 0x2a,
215 			 SCSI_TIMEOUT, 3, NULL);
216 }
217 
218 static int scsi_realloc_sdev_budget_map(struct scsi_device *sdev,
219 					unsigned int depth)
220 {
221 	int new_shift = sbitmap_calculate_shift(depth);
222 	bool need_alloc = !sdev->budget_map.map;
223 	bool need_free = false;
224 	unsigned int memflags;
225 	int ret;
226 	struct sbitmap sb_backup;
227 
228 	depth = min_t(unsigned int, depth, scsi_device_max_queue_depth(sdev));
229 
230 	/*
231 	 * realloc if new shift is calculated, which is caused by setting
232 	 * up one new default queue depth after calling ->sdev_configure
233 	 */
234 	if (!need_alloc && new_shift != sdev->budget_map.shift)
235 		need_alloc = need_free = true;
236 
237 	if (!need_alloc)
238 		return 0;
239 
240 	/*
241 	 * Request queue has to be frozen for reallocating budget map,
242 	 * and here disk isn't added yet, so freezing is pretty fast
243 	 */
244 	if (need_free) {
245 		memflags = blk_mq_freeze_queue(sdev->request_queue);
246 		sb_backup = sdev->budget_map;
247 	}
248 	ret = sbitmap_init_node(&sdev->budget_map,
249 				scsi_device_max_queue_depth(sdev),
250 				new_shift, GFP_NOIO,
251 				sdev->request_queue->node, false, true);
252 	if (!ret)
253 		sbitmap_resize(&sdev->budget_map, depth);
254 
255 	if (need_free) {
256 		if (ret)
257 			sdev->budget_map = sb_backup;
258 		else
259 			sbitmap_free(&sb_backup);
260 		ret = 0;
261 		blk_mq_unfreeze_queue(sdev->request_queue, memflags);
262 	}
263 	return ret;
264 }
265 
266 /**
267  * scsi_alloc_sdev - allocate and setup a scsi_Device
268  * @starget: which target to allocate a &scsi_device for
269  * @lun: which lun
270  * @hostdata: usually NULL and set by ->sdev_init instead
271  *
272  * Description:
273  *     Allocate, initialize for io, and return a pointer to a scsi_Device.
274  *     Stores the @shost, @channel, @id, and @lun in the scsi_Device, and
275  *     adds scsi_Device to the appropriate list.
276  *
277  * Return value:
278  *     scsi_Device pointer, or NULL on failure.
279  **/
280 static struct scsi_device *scsi_alloc_sdev(struct scsi_target *starget,
281 					   u64 lun, void *hostdata)
282 {
283 	unsigned int depth;
284 	struct scsi_device *sdev;
285 	struct request_queue *q;
286 	int display_failure_msg = 1, ret;
287 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
288 	struct queue_limits lim;
289 
290 	sdev = kzalloc(sizeof(*sdev) + shost->transportt->device_size,
291 		       GFP_KERNEL);
292 	if (!sdev)
293 		goto out;
294 
295 	strscpy(sdev->vendor, scsi_null_device_strs);
296 	strscpy(sdev->model, scsi_null_device_strs);
297 	strscpy(sdev->rev, scsi_null_device_strs);
298 	sdev->host = shost;
299 	sdev->queue_ramp_up_period = SCSI_DEFAULT_RAMP_UP_PERIOD;
300 	sdev->id = starget->id;
301 	sdev->lun = lun;
302 	sdev->channel = starget->channel;
303 	mutex_init(&sdev->state_mutex);
304 	sdev->sdev_state = SDEV_CREATED;
305 	INIT_LIST_HEAD(&sdev->siblings);
306 	INIT_LIST_HEAD(&sdev->same_target_siblings);
307 	INIT_LIST_HEAD(&sdev->starved_entry);
308 	INIT_LIST_HEAD(&sdev->event_list);
309 	spin_lock_init(&sdev->list_lock);
310 	mutex_init(&sdev->inquiry_mutex);
311 	INIT_WORK(&sdev->event_work, scsi_evt_thread);
312 	INIT_WORK(&sdev->requeue_work, scsi_requeue_run_queue);
313 
314 	sdev->sdev_gendev.parent = get_device(&starget->dev);
315 	sdev->sdev_target = starget;
316 
317 	/* usually NULL and set by ->sdev_init instead */
318 	sdev->hostdata = hostdata;
319 
320 	/* if the device needs this changing, it may do so in the
321 	 * sdev_configure function */
322 	sdev->max_device_blocked = SCSI_DEFAULT_DEVICE_BLOCKED;
323 
324 	/*
325 	 * Some low level driver could use device->type
326 	 */
327 	sdev->type = -1;
328 
329 	/*
330 	 * Assume that the device will have handshaking problems,
331 	 * and then fix this field later if it turns out it
332 	 * doesn't
333 	 */
334 	sdev->borken = 1;
335 
336 	sdev->sg_reserved_size = INT_MAX;
337 
338 	scsi_init_limits(shost, &lim);
339 	q = blk_mq_alloc_queue(&sdev->host->tag_set, &lim, sdev);
340 	if (IS_ERR(q)) {
341 		/* release fn is set up in scsi_sysfs_device_initialise, so
342 		 * have to free and put manually here */
343 		put_device(&starget->dev);
344 		kfree(sdev);
345 		goto out;
346 	}
347 	kref_get(&sdev->host->tagset_refcnt);
348 	sdev->request_queue = q;
349 
350 	scsi_sysfs_device_initialize(sdev);
351 
352 	if (scsi_device_is_pseudo_dev(sdev))
353 		return sdev;
354 
355 	depth = sdev->host->cmd_per_lun ?: 1;
356 
357 	/*
358 	 * Use .can_queue as budget map's depth because we have to
359 	 * support adjusting queue depth from sysfs. Meantime use
360 	 * default device queue depth to figure out sbitmap shift
361 	 * since we use this queue depth most of times.
362 	 */
363 	if (scsi_realloc_sdev_budget_map(sdev, depth))
364 		goto out_device_destroy;
365 
366 	scsi_change_queue_depth(sdev, depth);
367 
368 	if (shost->hostt->sdev_init) {
369 		ret = shost->hostt->sdev_init(sdev);
370 		if (ret) {
371 			/*
372 			 * if LLDD reports slave not present, don't clutter
373 			 * console with alloc failure messages
374 			 */
375 			if (ret == -ENXIO)
376 				display_failure_msg = 0;
377 			goto out_device_destroy;
378 		}
379 	}
380 
381 	return sdev;
382 
383 out_device_destroy:
384 	__scsi_remove_device(sdev);
385 out:
386 	if (display_failure_msg)
387 		printk(ALLOC_FAILURE_MSG, __func__);
388 	return NULL;
389 }
390 
391 static void scsi_target_destroy(struct scsi_target *starget)
392 {
393 	struct device *dev = &starget->dev;
394 	struct Scsi_Host *shost = dev_to_shost(dev->parent);
395 	unsigned long flags;
396 
397 	BUG_ON(starget->state == STARGET_DEL);
398 	starget->state = STARGET_DEL;
399 	transport_destroy_device(dev);
400 	spin_lock_irqsave(shost->host_lock, flags);
401 	if (shost->hostt->target_destroy)
402 		shost->hostt->target_destroy(starget);
403 	list_del_init(&starget->siblings);
404 	spin_unlock_irqrestore(shost->host_lock, flags);
405 	put_device(dev);
406 }
407 
408 static void scsi_target_dev_release(struct device *dev)
409 {
410 	struct device *parent = dev->parent;
411 	struct scsi_target *starget = to_scsi_target(dev);
412 
413 	kfree(starget);
414 	put_device(parent);
415 }
416 
417 static const struct device_type scsi_target_type = {
418 	.name =		"scsi_target",
419 	.release =	scsi_target_dev_release,
420 };
421 
422 int scsi_is_target_device(const struct device *dev)
423 {
424 	return dev->type == &scsi_target_type;
425 }
426 EXPORT_SYMBOL(scsi_is_target_device);
427 
428 static struct scsi_target *__scsi_find_target(struct device *parent,
429 					      int channel, uint id)
430 {
431 	struct scsi_target *starget, *found_starget = NULL;
432 	struct Scsi_Host *shost = dev_to_shost(parent);
433 	/*
434 	 * Search for an existing target for this sdev.
435 	 */
436 	list_for_each_entry(starget, &shost->__targets, siblings) {
437 		if (starget->id == id &&
438 		    starget->channel == channel) {
439 			found_starget = starget;
440 			break;
441 		}
442 	}
443 	if (found_starget)
444 		get_device(&found_starget->dev);
445 
446 	return found_starget;
447 }
448 
449 /**
450  * scsi_target_reap_ref_release - remove target from visibility
451  * @kref: the reap_ref in the target being released
452  *
453  * Called on last put of reap_ref, which is the indication that no device
454  * under this target is visible anymore, so render the target invisible in
455  * sysfs.  Note: we have to be in user context here because the target reaps
456  * should be done in places where the scsi device visibility is being removed.
457  */
458 static void scsi_target_reap_ref_release(struct kref *kref)
459 {
460 	struct scsi_target *starget
461 		= container_of(kref, struct scsi_target, reap_ref);
462 
463 	/*
464 	 * if we get here and the target is still in a CREATED state that
465 	 * means it was allocated but never made visible (because a scan
466 	 * turned up no LUNs), so don't call device_del() on it.
467 	 */
468 	if ((starget->state != STARGET_CREATED) &&
469 	    (starget->state != STARGET_CREATED_REMOVE)) {
470 		transport_remove_device(&starget->dev);
471 		device_del(&starget->dev);
472 	}
473 	scsi_target_destroy(starget);
474 }
475 
476 static void scsi_target_reap_ref_put(struct scsi_target *starget)
477 {
478 	kref_put(&starget->reap_ref, scsi_target_reap_ref_release);
479 }
480 
481 /**
482  * scsi_alloc_target - allocate a new or find an existing target
483  * @parent:	parent of the target (need not be a scsi host)
484  * @channel:	target channel number (zero if no channels)
485  * @id:		target id number
486  *
487  * Return an existing target if one exists, provided it hasn't already
488  * gone into STARGET_DEL state, otherwise allocate a new target.
489  *
490  * The target is returned with an incremented reference, so the caller
491  * is responsible for both reaping and doing a last put
492  */
493 static struct scsi_target *scsi_alloc_target(struct device *parent,
494 					     int channel, uint id)
495 {
496 	struct Scsi_Host *shost = dev_to_shost(parent);
497 	struct device *dev = NULL;
498 	unsigned long flags;
499 	const int size = sizeof(struct scsi_target)
500 		+ shost->transportt->target_size;
501 	struct scsi_target *starget;
502 	struct scsi_target *found_target;
503 	int error, ref_got;
504 
505 	starget = kzalloc(size, GFP_KERNEL);
506 	if (!starget) {
507 		printk(KERN_ERR "%s: allocation failure\n", __func__);
508 		return NULL;
509 	}
510 	dev = &starget->dev;
511 	device_initialize(dev);
512 	kref_init(&starget->reap_ref);
513 	dev->parent = get_device(parent);
514 	dev_set_name(dev, "target%d:%d:%d", shost->host_no, channel, id);
515 	dev->bus = &scsi_bus_type;
516 	dev->type = &scsi_target_type;
517 	scsi_enable_async_suspend(dev);
518 	starget->id = id;
519 	starget->channel = channel;
520 	starget->can_queue = 0;
521 	INIT_LIST_HEAD(&starget->siblings);
522 	INIT_LIST_HEAD(&starget->devices);
523 	starget->state = STARGET_CREATED;
524 	starget->scsi_level = SCSI_2;
525 	starget->max_target_blocked = SCSI_DEFAULT_TARGET_BLOCKED;
526  retry:
527 	spin_lock_irqsave(shost->host_lock, flags);
528 
529 	found_target = __scsi_find_target(parent, channel, id);
530 	if (found_target)
531 		goto found;
532 
533 	list_add_tail(&starget->siblings, &shost->__targets);
534 	spin_unlock_irqrestore(shost->host_lock, flags);
535 	/* allocate and add */
536 	transport_setup_device(dev);
537 	if (shost->hostt->target_alloc) {
538 		error = shost->hostt->target_alloc(starget);
539 
540 		if(error) {
541 			if (error != -ENXIO)
542 				dev_err(dev, "target allocation failed, error %d\n", error);
543 			/* don't want scsi_target_reap to do the final
544 			 * put because it will be under the host lock */
545 			scsi_target_destroy(starget);
546 			return NULL;
547 		}
548 	}
549 	get_device(dev);
550 
551 	return starget;
552 
553  found:
554 	/*
555 	 * release routine already fired if kref is zero, so if we can still
556 	 * take the reference, the target must be alive.  If we can't, it must
557 	 * be dying and we need to wait for a new target
558 	 */
559 	ref_got = kref_get_unless_zero(&found_target->reap_ref);
560 
561 	spin_unlock_irqrestore(shost->host_lock, flags);
562 	if (ref_got) {
563 		put_device(dev);
564 		return found_target;
565 	}
566 	/*
567 	 * Unfortunately, we found a dying target; need to wait until it's
568 	 * dead before we can get a new one.  There is an anomaly here.  We
569 	 * *should* call scsi_target_reap() to balance the kref_get() of the
570 	 * reap_ref above.  However, since the target being released, it's
571 	 * already invisible and the reap_ref is irrelevant.  If we call
572 	 * scsi_target_reap() we might spuriously do another device_del() on
573 	 * an already invisible target.
574 	 */
575 	put_device(&found_target->dev);
576 	/*
577 	 * length of time is irrelevant here, we just want to yield the CPU
578 	 * for a tick to avoid busy waiting for the target to die.
579 	 */
580 	msleep(1);
581 	goto retry;
582 }
583 
584 /**
585  * scsi_target_reap - check to see if target is in use and destroy if not
586  * @starget: target to be checked
587  *
588  * This is used after removing a LUN or doing a last put of the target
589  * it checks atomically that nothing is using the target and removes
590  * it if so.
591  */
592 void scsi_target_reap(struct scsi_target *starget)
593 {
594 	/*
595 	 * serious problem if this triggers: STARGET_DEL is only set in the if
596 	 * the reap_ref drops to zero, so we're trying to do another final put
597 	 * on an already released kref
598 	 */
599 	BUG_ON(starget->state == STARGET_DEL);
600 	scsi_target_reap_ref_put(starget);
601 }
602 
603 /**
604  * scsi_sanitize_inquiry_string - remove non-graphical chars from an
605  *                                INQUIRY result string
606  * @s: INQUIRY result string to sanitize
607  * @len: length of the string
608  *
609  * Description:
610  *	The SCSI spec says that INQUIRY vendor, product, and revision
611  *	strings must consist entirely of graphic ASCII characters,
612  *	padded on the right with spaces.  Since not all devices obey
613  *	this rule, we will replace non-graphic or non-ASCII characters
614  *	with spaces.  Exception: a NUL character is interpreted as a
615  *	string terminator, so all the following characters are set to
616  *	spaces.
617  **/
618 void scsi_sanitize_inquiry_string(unsigned char *s, int len)
619 {
620 	int terminated = 0;
621 
622 	for (; len > 0; (--len, ++s)) {
623 		if (*s == 0)
624 			terminated = 1;
625 		if (terminated || *s < 0x20 || *s > 0x7e)
626 			*s = ' ';
627 	}
628 }
629 EXPORT_SYMBOL(scsi_sanitize_inquiry_string);
630 
631 
632 /**
633  * scsi_probe_lun - probe a single LUN using a SCSI INQUIRY
634  * @sdev:	scsi_device to probe
635  * @inq_result:	area to store the INQUIRY result
636  * @result_len: len of inq_result
637  * @bflags:	store any bflags found here
638  *
639  * Description:
640  *     Probe the lun associated with @req using a standard SCSI INQUIRY;
641  *
642  *     If the INQUIRY is successful, zero is returned and the
643  *     INQUIRY data is in @inq_result; the scsi_level and INQUIRY length
644  *     are copied to the scsi_device any flags value is stored in *@bflags.
645  **/
646 static int scsi_probe_lun(struct scsi_device *sdev, unsigned char *inq_result,
647 			  int result_len, blist_flags_t *bflags)
648 {
649 	unsigned char scsi_cmd[MAX_COMMAND_SIZE];
650 	int first_inquiry_len, try_inquiry_len, next_inquiry_len;
651 	int response_len = 0;
652 	int pass, count, result, resid;
653 	struct scsi_failure failure_defs[] = {
654 		/*
655 		 * not-ready to ready transition [asc/ascq=0x28/0x0] or
656 		 * power-on, reset [asc/ascq=0x29/0x0], continue. INQUIRY
657 		 * should not yield UNIT_ATTENTION but many buggy devices do
658 		 * so anyway.
659 		 */
660 		{
661 			.sense = UNIT_ATTENTION,
662 			.asc = 0x28,
663 			.result = SAM_STAT_CHECK_CONDITION,
664 		},
665 		{
666 			.sense = UNIT_ATTENTION,
667 			.asc = 0x29,
668 			.result = SAM_STAT_CHECK_CONDITION,
669 		},
670 		{
671 			.allowed = 1,
672 			.result = DID_TIME_OUT << 16,
673 		},
674 		{}
675 	};
676 	struct scsi_failures failures = {
677 		.total_allowed = 3,
678 		.failure_definitions = failure_defs,
679 	};
680 	const struct scsi_exec_args exec_args = {
681 		.resid = &resid,
682 		.failures = &failures,
683 	};
684 
685 	*bflags = 0;
686 
687 	/* Perform up to 3 passes.  The first pass uses a conservative
688 	 * transfer length of 36 unless sdev->inquiry_len specifies a
689 	 * different value. */
690 	first_inquiry_len = sdev->inquiry_len ? sdev->inquiry_len : 36;
691 	try_inquiry_len = first_inquiry_len;
692 	pass = 1;
693 
694  next_pass:
695 	SCSI_LOG_SCAN_BUS(3, sdev_printk(KERN_INFO, sdev,
696 				"scsi scan: INQUIRY pass %d length %d\n",
697 				pass, try_inquiry_len));
698 
699 	/* Each pass gets up to three chances to ignore Unit Attention */
700 	scsi_failures_reset_retries(&failures);
701 
702 	for (count = 0; count < 3; ++count) {
703 		memset(scsi_cmd, 0, 6);
704 		scsi_cmd[0] = INQUIRY;
705 		scsi_cmd[4] = (unsigned char) try_inquiry_len;
706 
707 		memset(inq_result, 0, try_inquiry_len);
708 
709 		result = scsi_execute_cmd(sdev,  scsi_cmd, REQ_OP_DRV_IN,
710 					  inq_result, try_inquiry_len,
711 					  HZ / 2 + HZ * scsi_inq_timeout, 3,
712 					  &exec_args);
713 
714 		SCSI_LOG_SCAN_BUS(3, sdev_printk(KERN_INFO, sdev,
715 				"scsi scan: INQUIRY %s with code 0x%x\n",
716 				result ? "failed" : "successful", result));
717 
718 		if (result == 0) {
719 			/*
720 			 * if nothing was transferred, we try
721 			 * again. It's a workaround for some USB
722 			 * devices.
723 			 */
724 			if (resid == try_inquiry_len)
725 				continue;
726 		}
727 		break;
728 	}
729 
730 	if (result == 0) {
731 		scsi_sanitize_inquiry_string(&inq_result[INQUIRY_VENDOR_OFFSET],
732 					     INQUIRY_VENDOR_LEN);
733 		scsi_sanitize_inquiry_string(&inq_result[INQUIRY_MODEL_OFFSET],
734 					     INQUIRY_MODEL_LEN);
735 		scsi_sanitize_inquiry_string(
736 			&inq_result[INQUIRY_REVISION_OFFSET],
737 			INQUIRY_REVISION_LEN);
738 
739 		response_len = inq_result[4] + 5;
740 		if (response_len > 255)
741 			response_len = first_inquiry_len;	/* sanity */
742 
743 		/*
744 		 * Get any flags for this device.
745 		 *
746 		 * XXX add a bflags to scsi_device, and replace the
747 		 * corresponding bit fields in scsi_device, so bflags
748 		 * need not be passed as an argument.
749 		 */
750 		*bflags = scsi_get_device_flags(sdev,
751 				&inq_result[INQUIRY_VENDOR_OFFSET],
752 				&inq_result[INQUIRY_MODEL_OFFSET]);
753 
754 		/* When the first pass succeeds we gain information about
755 		 * what larger transfer lengths might work. */
756 		if (pass == 1) {
757 			if (BLIST_INQUIRY_36 & *bflags)
758 				next_inquiry_len = 36;
759 			/*
760 			 * LLD specified a maximum sdev->inquiry_len
761 			 * but device claims it has more data. Capping
762 			 * the length only makes sense for legacy
763 			 * devices. If a device supports SPC-4 (2014)
764 			 * or newer, assume that it is safe to ask for
765 			 * as much as the device says it supports.
766 			 */
767 			else if (sdev->inquiry_len &&
768 				 response_len > sdev->inquiry_len &&
769 				 (inq_result[2] & 0x7) < 6) /* SPC-4 */
770 				next_inquiry_len = sdev->inquiry_len;
771 			else
772 				next_inquiry_len = response_len;
773 
774 			/* If more data is available perform the second pass */
775 			if (next_inquiry_len > try_inquiry_len) {
776 				try_inquiry_len = next_inquiry_len;
777 				pass = 2;
778 				goto next_pass;
779 			}
780 		}
781 
782 	} else if (pass == 2) {
783 		sdev_printk(KERN_INFO, sdev,
784 			    "scsi scan: %d byte inquiry failed.  "
785 			    "Consider BLIST_INQUIRY_36 for this device\n",
786 			    try_inquiry_len);
787 
788 		/* If this pass failed, the third pass goes back and transfers
789 		 * the same amount as we successfully got in the first pass. */
790 		try_inquiry_len = first_inquiry_len;
791 		pass = 3;
792 		goto next_pass;
793 	}
794 
795 	/* If the last transfer attempt got an error, assume the
796 	 * peripheral doesn't exist or is dead. */
797 	if (result)
798 		return -EIO;
799 
800 	/* Don't report any more data than the device says is valid */
801 	sdev->inquiry_len = min(try_inquiry_len, response_len);
802 
803 	/*
804 	 * XXX Abort if the response length is less than 36? If less than
805 	 * 32, the lookup of the device flags (above) could be invalid,
806 	 * and it would be possible to take an incorrect action - we do
807 	 * not want to hang because of a short INQUIRY. On the flip side,
808 	 * if the device is spun down or becoming ready (and so it gives a
809 	 * short INQUIRY), an abort here prevents any further use of the
810 	 * device, including spin up.
811 	 *
812 	 * On the whole, the best approach seems to be to assume the first
813 	 * 36 bytes are valid no matter what the device says.  That's
814 	 * better than copying < 36 bytes to the inquiry-result buffer
815 	 * and displaying garbage for the Vendor, Product, or Revision
816 	 * strings.
817 	 */
818 	if (sdev->inquiry_len < 36) {
819 		if (!sdev->host->short_inquiry) {
820 			shost_printk(KERN_INFO, sdev->host,
821 				    "scsi scan: INQUIRY result too short (%d),"
822 				    " using 36\n", sdev->inquiry_len);
823 			sdev->host->short_inquiry = 1;
824 		}
825 		sdev->inquiry_len = 36;
826 	}
827 
828 	/*
829 	 * Related to the above issue:
830 	 *
831 	 * XXX Devices (disk or all?) should be sent a TEST UNIT READY,
832 	 * and if not ready, sent a START_STOP to start (maybe spin up) and
833 	 * then send the INQUIRY again, since the INQUIRY can change after
834 	 * a device is initialized.
835 	 *
836 	 * Ideally, start a device if explicitly asked to do so.  This
837 	 * assumes that a device is spun up on power on, spun down on
838 	 * request, and then spun up on request.
839 	 */
840 
841 	/*
842 	 * The scanning code needs to know the scsi_level, even if no
843 	 * device is attached at LUN 0 (SCSI_SCAN_TARGET_PRESENT) so
844 	 * non-zero LUNs can be scanned.
845 	 */
846 	sdev->scsi_level = inq_result[2] & 0x0f;
847 	if (sdev->scsi_level >= 2 ||
848 	    (sdev->scsi_level == 1 && (inq_result[3] & 0x0f) == 1))
849 		sdev->scsi_level++;
850 	sdev->sdev_target->scsi_level = sdev->scsi_level;
851 
852 	/*
853 	 * If SCSI-2 or lower, and if the transport requires it,
854 	 * store the LUN value in CDB[1].
855 	 */
856 	sdev->lun_in_cdb = 0;
857 	if (sdev->scsi_level <= SCSI_2 &&
858 	    sdev->scsi_level != SCSI_UNKNOWN &&
859 	    !sdev->host->no_scsi2_lun_in_cdb)
860 		sdev->lun_in_cdb = 1;
861 
862 	return 0;
863 }
864 
865 /**
866  * scsi_add_lun - allocate and fully initialize a scsi_device
867  * @sdev:	holds information to be stored in the new scsi_device
868  * @inq_result:	holds the result of a previous INQUIRY to the LUN
869  * @bflags:	black/white list flag
870  * @async:	1 if this device is being scanned asynchronously
871  *
872  * Description:
873  *     Initialize the scsi_device @sdev.  Optionally set fields based
874  *     on values in *@bflags.
875  *
876  * Return:
877  *     SCSI_SCAN_NO_RESPONSE: could not allocate or setup a scsi_device
878  *     SCSI_SCAN_LUN_PRESENT: a new scsi_device was allocated and initialized
879  **/
880 static int scsi_add_lun(struct scsi_device *sdev, unsigned char *inq_result,
881 		blist_flags_t *bflags, int async)
882 {
883 	const struct scsi_host_template *hostt = sdev->host->hostt;
884 	struct queue_limits lim;
885 	int ret;
886 
887 	/*
888 	 * XXX do not save the inquiry, since it can change underneath us,
889 	 * save just vendor/model/rev.
890 	 *
891 	 * Rather than save it and have an ioctl that retrieves the saved
892 	 * value, have an ioctl that executes the same INQUIRY code used
893 	 * in scsi_probe_lun, let user level programs doing INQUIRY
894 	 * scanning run at their own risk, or supply a user level program
895 	 * that can correctly scan.
896 	 */
897 
898 	/*
899 	 * Copy at least 36 bytes of INQUIRY data, so that we don't
900 	 * dereference unallocated memory when accessing the Vendor,
901 	 * Product, and Revision strings.  Badly behaved devices may set
902 	 * the INQUIRY Additional Length byte to a small value, indicating
903 	 * these strings are invalid, but often they contain plausible data
904 	 * nonetheless.  It doesn't matter if the device sent < 36 bytes
905 	 * total, since scsi_probe_lun() initializes inq_result with 0s.
906 	 */
907 	sdev->inquiry = kmemdup(inq_result,
908 				max_t(size_t, sdev->inquiry_len, 36),
909 				GFP_KERNEL);
910 	if (sdev->inquiry == NULL)
911 		return SCSI_SCAN_NO_RESPONSE;
912 
913 	strscpy(sdev->vendor, sdev->inquiry + INQUIRY_VENDOR_OFFSET);
914 	strscpy(sdev->model, sdev->inquiry + INQUIRY_MODEL_OFFSET);
915 	/*
916 	 * memcpy() instead of strscpy() because strscpy() would read past
917 	 * the end of sdev->inquiry if its length is exactly 36 bytes.
918 	 */
919 	memcpy(sdev->rev, sdev->inquiry + INQUIRY_REVISION_OFFSET,
920 	       INQUIRY_REVISION_LEN);
921 	sdev->rev[INQUIRY_REVISION_LEN] = '\0';
922 
923 	sdev->is_ata = strncmp(sdev->vendor, "ATA     ", 8) == 0;
924 	if (sdev->is_ata) {
925 		/*
926 		 * sata emulation layer device.  This is a hack to work around
927 		 * the SATL power management specifications which state that
928 		 * when the SATL detects the device has gone into standby
929 		 * mode, it shall respond with NOT READY.
930 		 */
931 		sdev->allow_restart = 1;
932 	}
933 
934 	if (*bflags & BLIST_ISROM) {
935 		sdev->type = TYPE_ROM;
936 		sdev->removable = 1;
937 	} else {
938 		sdev->type = (inq_result[0] & 0x1f);
939 		sdev->removable = (inq_result[1] & 0x80) >> 7;
940 
941 		/*
942 		 * some devices may respond with wrong type for
943 		 * well-known logical units. Force well-known type
944 		 * to enumerate them correctly.
945 		 */
946 		if (scsi_is_wlun(sdev->lun) && sdev->type != TYPE_WLUN) {
947 			sdev_printk(KERN_WARNING, sdev,
948 				"%s: correcting incorrect peripheral device type 0x%x for W-LUN 0x%16xhN\n",
949 				__func__, sdev->type, (unsigned int)sdev->lun);
950 			sdev->type = TYPE_WLUN;
951 		}
952 
953 	}
954 
955 	if (sdev->type == TYPE_RBC || sdev->type == TYPE_ROM) {
956 		/* RBC and MMC devices can return SCSI-3 compliance and yet
957 		 * still not support REPORT LUNS, so make them act as
958 		 * BLIST_NOREPORTLUN unless BLIST_REPORTLUN2 is
959 		 * specifically set */
960 		if ((*bflags & BLIST_REPORTLUN2) == 0)
961 			*bflags |= BLIST_NOREPORTLUN;
962 	}
963 
964 	/*
965 	 * For a peripheral qualifier (PQ) value of 1 (001b), the SCSI
966 	 * spec says: The device server is capable of supporting the
967 	 * specified peripheral device type on this logical unit. However,
968 	 * the physical device is not currently connected to this logical
969 	 * unit.
970 	 *
971 	 * The above is vague, as it implies that we could treat 001 and
972 	 * 011 the same. Stay compatible with previous code, and create a
973 	 * scsi_device for a PQ of 1
974 	 *
975 	 * Don't set the device offline here; rather let the upper
976 	 * level drivers eval the PQ to decide whether they should
977 	 * attach. So remove ((inq_result[0] >> 5) & 7) == 1 check.
978 	 */
979 
980 	sdev->inq_periph_qual = (inq_result[0] >> 5) & 7;
981 	sdev->lockable = sdev->removable;
982 	sdev->soft_reset = (inq_result[7] & 1) && ((inq_result[3] & 7) == 2);
983 
984 	if (sdev->scsi_level >= SCSI_3 ||
985 			(sdev->inquiry_len > 56 && inq_result[56] & 0x04))
986 		sdev->ppr = 1;
987 	if (inq_result[7] & 0x60)
988 		sdev->wdtr = 1;
989 	if (inq_result[7] & 0x10)
990 		sdev->sdtr = 1;
991 
992 	sdev_printk(KERN_NOTICE, sdev, "%s %.8s %.16s %.4s PQ: %d "
993 			"ANSI: %d%s\n", scsi_device_type(sdev->type),
994 			sdev->vendor, sdev->model, sdev->rev,
995 			sdev->inq_periph_qual, inq_result[2] & 0x07,
996 			(inq_result[3] & 0x0f) == 1 ? " CCS" : "");
997 
998 	if ((sdev->scsi_level >= SCSI_2) && (inq_result[7] & 2) &&
999 	    !(*bflags & BLIST_NOTQ)) {
1000 		sdev->tagged_supported = 1;
1001 		sdev->simple_tags = 1;
1002 	}
1003 
1004 	/*
1005 	 * Some devices (Texel CD ROM drives) have handshaking problems
1006 	 * when used with the Seagate controllers. borken is initialized
1007 	 * to 1, and then set it to 0 here.
1008 	 */
1009 	if ((*bflags & BLIST_BORKEN) == 0)
1010 		sdev->borken = 0;
1011 
1012 	if (*bflags & BLIST_NO_ULD_ATTACH)
1013 		sdev->no_uld_attach = 1;
1014 
1015 	/*
1016 	 * Apparently some really broken devices (contrary to the SCSI
1017 	 * standards) need to be selected without asserting ATN
1018 	 */
1019 	if (*bflags & BLIST_SELECT_NO_ATN)
1020 		sdev->select_no_atn = 1;
1021 
1022 	/*
1023 	 * Some devices may not want to have a start command automatically
1024 	 * issued when a device is added.
1025 	 */
1026 	if (*bflags & BLIST_NOSTARTONADD)
1027 		sdev->no_start_on_add = 1;
1028 
1029 	if (*bflags & BLIST_SINGLELUN)
1030 		scsi_target(sdev)->single_lun = 1;
1031 
1032 	sdev->use_10_for_rw = 1;
1033 
1034 	/* some devices don't like REPORT SUPPORTED OPERATION CODES
1035 	 * and will simply timeout causing sd_mod init to take a very
1036 	 * very long time */
1037 	if (*bflags & BLIST_NO_RSOC)
1038 		sdev->no_report_opcodes = 1;
1039 
1040 	/* set the device running here so that slave configure
1041 	 * may do I/O */
1042 	mutex_lock(&sdev->state_mutex);
1043 	ret = scsi_device_set_state(sdev, SDEV_RUNNING);
1044 	if (ret)
1045 		ret = scsi_device_set_state(sdev, SDEV_BLOCK);
1046 	mutex_unlock(&sdev->state_mutex);
1047 
1048 	if (ret) {
1049 		sdev_printk(KERN_ERR, sdev,
1050 			    "in wrong state %s to complete scan\n",
1051 			    scsi_device_state_name(sdev->sdev_state));
1052 		return SCSI_SCAN_NO_RESPONSE;
1053 	}
1054 
1055 	if (*bflags & BLIST_NOT_LOCKABLE)
1056 		sdev->lockable = 0;
1057 
1058 	if (*bflags & BLIST_RETRY_HWERROR)
1059 		sdev->retry_hwerror = 1;
1060 
1061 	if (*bflags & BLIST_NO_DIF)
1062 		sdev->no_dif = 1;
1063 
1064 	if (*bflags & BLIST_UNMAP_LIMIT_WS)
1065 		sdev->unmap_limit_for_ws = 1;
1066 
1067 	if (*bflags & BLIST_IGN_MEDIA_CHANGE)
1068 		sdev->ignore_media_change = 1;
1069 
1070 	sdev->eh_timeout = SCSI_DEFAULT_EH_TIMEOUT;
1071 
1072 	if (*bflags & BLIST_TRY_VPD_PAGES)
1073 		sdev->try_vpd_pages = 1;
1074 	else if (*bflags & BLIST_SKIP_VPD_PAGES)
1075 		sdev->skip_vpd_pages = 1;
1076 
1077 	if (*bflags & BLIST_NO_VPD_SIZE)
1078 		sdev->no_vpd_size = 1;
1079 
1080 	transport_configure_device(&sdev->sdev_gendev);
1081 
1082 	sdev->sdev_bflags = *bflags;
1083 
1084 	if (scsi_device_is_pseudo_dev(sdev))
1085 		return SCSI_SCAN_LUN_PRESENT;
1086 
1087 	/*
1088 	 * No need to freeze the queue as it isn't reachable to anyone else yet.
1089 	 */
1090 	lim = queue_limits_start_update(sdev->request_queue);
1091 	if (*bflags & BLIST_MAX_512)
1092 		lim.max_hw_sectors = 512;
1093 	else if (*bflags & BLIST_MAX_1024)
1094 		lim.max_hw_sectors = 1024;
1095 
1096 	if (hostt->sdev_configure)
1097 		ret = hostt->sdev_configure(sdev, &lim);
1098 	if (ret) {
1099 		queue_limits_cancel_update(sdev->request_queue);
1100 		/*
1101 		 * If the LLDD reports device not present, don't clutter the
1102 		 * console with failure messages.
1103 		 */
1104 		if (ret != -ENXIO)
1105 			sdev_printk(KERN_ERR, sdev,
1106 				"failed to configure device\n");
1107 		return SCSI_SCAN_NO_RESPONSE;
1108 	}
1109 
1110 	ret = queue_limits_commit_update(sdev->request_queue, &lim);
1111 	if (ret) {
1112 		sdev_printk(KERN_ERR, sdev, "failed to apply queue limits.\n");
1113 		return SCSI_SCAN_NO_RESPONSE;
1114 	}
1115 
1116 	/*
1117 	 * The queue_depth is often changed in ->sdev_configure.
1118 	 *
1119 	 * Set up budget map again since memory consumption of the map depends
1120 	 * on actual queue depth.
1121 	 */
1122 	if (hostt->sdev_configure)
1123 		scsi_realloc_sdev_budget_map(sdev, sdev->queue_depth);
1124 
1125 	if (sdev->scsi_level >= SCSI_3)
1126 		scsi_attach_vpd(sdev);
1127 
1128 	scsi_cdl_check(sdev);
1129 
1130 	sdev->max_queue_depth = sdev->queue_depth;
1131 	WARN_ON_ONCE(sdev->max_queue_depth > sdev->budget_map.depth);
1132 
1133 	/*
1134 	 * Ok, the device is now all set up, we can
1135 	 * register it and tell the rest of the kernel
1136 	 * about it.
1137 	 */
1138 	if (!async && scsi_sysfs_add_sdev(sdev) != 0)
1139 		return SCSI_SCAN_NO_RESPONSE;
1140 
1141 	return SCSI_SCAN_LUN_PRESENT;
1142 }
1143 
1144 #ifdef CONFIG_SCSI_LOGGING
1145 /**
1146  * scsi_inq_str - print INQUIRY data from min to max index, strip trailing whitespace
1147  * @buf:   Output buffer with at least end-first+1 bytes of space
1148  * @inq:   Inquiry buffer (input)
1149  * @first: Offset of string into inq
1150  * @end:   Index after last character in inq
1151  */
1152 static unsigned char *scsi_inq_str(unsigned char *buf, unsigned char *inq,
1153 				   unsigned first, unsigned end)
1154 {
1155 	unsigned term = 0, idx;
1156 
1157 	for (idx = 0; idx + first < end && idx + first < inq[4] + 5; idx++) {
1158 		if (inq[idx+first] > ' ') {
1159 			buf[idx] = inq[idx+first];
1160 			term = idx+1;
1161 		} else {
1162 			buf[idx] = ' ';
1163 		}
1164 	}
1165 	buf[term] = 0;
1166 	return buf;
1167 }
1168 #endif
1169 
1170 /**
1171  * scsi_probe_and_add_lun - probe a LUN, if a LUN is found add it
1172  * @starget:	pointer to target device structure
1173  * @lun:	LUN of target device
1174  * @bflagsp:	store bflags here if not NULL
1175  * @sdevp:	probe the LUN corresponding to this scsi_device
1176  * @rescan:     if not equal to SCSI_SCAN_INITIAL skip some code only
1177  *              needed on first scan
1178  * @hostdata:	passed to scsi_alloc_sdev()
1179  *
1180  * Description:
1181  *     Call scsi_probe_lun, if a LUN with an attached device is found,
1182  *     allocate and set it up by calling scsi_add_lun.
1183  *
1184  * Return:
1185  *
1186  *   - SCSI_SCAN_NO_RESPONSE: could not allocate or setup a scsi_device
1187  *   - SCSI_SCAN_TARGET_PRESENT: target responded, but no device is
1188  *         attached at the LUN
1189  *   - SCSI_SCAN_LUN_PRESENT: a new scsi_device was allocated and initialized
1190  **/
1191 static int scsi_probe_and_add_lun(struct scsi_target *starget,
1192 				  u64 lun, blist_flags_t *bflagsp,
1193 				  struct scsi_device **sdevp,
1194 				  enum scsi_scan_mode rescan,
1195 				  void *hostdata)
1196 {
1197 	struct scsi_device *sdev;
1198 	unsigned char *result;
1199 	blist_flags_t bflags;
1200 	int res = SCSI_SCAN_NO_RESPONSE, result_len = 256;
1201 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1202 
1203 	/*
1204 	 * The rescan flag is used as an optimization, the first scan of a
1205 	 * host adapter calls into here with rescan == 0.
1206 	 */
1207 	sdev = scsi_device_lookup_by_target(starget, lun);
1208 	if (sdev) {
1209 		if (rescan != SCSI_SCAN_INITIAL || !scsi_device_created(sdev)) {
1210 			SCSI_LOG_SCAN_BUS(3, sdev_printk(KERN_INFO, sdev,
1211 				"scsi scan: device exists on %s\n",
1212 				dev_name(&sdev->sdev_gendev)));
1213 			if (sdevp)
1214 				*sdevp = sdev;
1215 			else
1216 				scsi_device_put(sdev);
1217 
1218 			if (bflagsp)
1219 				*bflagsp = scsi_get_device_flags(sdev,
1220 								 sdev->vendor,
1221 								 sdev->model);
1222 			return SCSI_SCAN_LUN_PRESENT;
1223 		}
1224 		scsi_device_put(sdev);
1225 	} else
1226 		sdev = scsi_alloc_sdev(starget, lun, hostdata);
1227 	if (!sdev)
1228 		goto out;
1229 
1230 	if (scsi_device_is_pseudo_dev(sdev)) {
1231 		if (bflagsp)
1232 			*bflagsp = BLIST_NOLUN;
1233 		return SCSI_SCAN_LUN_PRESENT;
1234 	}
1235 
1236 	result = kmalloc(result_len, GFP_KERNEL);
1237 	if (!result)
1238 		goto out_free_sdev;
1239 
1240 	if (scsi_probe_lun(sdev, result, result_len, &bflags))
1241 		goto out_free_result;
1242 
1243 	if (bflagsp)
1244 		*bflagsp = bflags;
1245 	/*
1246 	 * result contains valid SCSI INQUIRY data.
1247 	 */
1248 	if ((result[0] >> 5) == 3) {
1249 		/*
1250 		 * For a Peripheral qualifier 3 (011b), the SCSI
1251 		 * spec says: The device server is not capable of
1252 		 * supporting a physical device on this logical
1253 		 * unit.
1254 		 *
1255 		 * For disks, this implies that there is no
1256 		 * logical disk configured at sdev->lun, but there
1257 		 * is a target id responding.
1258 		 */
1259 		SCSI_LOG_SCAN_BUS(2, sdev_printk(KERN_INFO, sdev, "scsi scan:"
1260 				   " peripheral qualifier of 3, device not"
1261 				   " added\n"))
1262 		if (lun == 0) {
1263 			SCSI_LOG_SCAN_BUS(1, {
1264 				unsigned char vend[9];
1265 				unsigned char mod[17];
1266 
1267 				sdev_printk(KERN_INFO, sdev,
1268 					"scsi scan: consider passing scsi_mod."
1269 					"dev_flags=%s:%s:0x240 or 0x1000240\n",
1270 					scsi_inq_str(vend, result, 8, 16),
1271 					scsi_inq_str(mod, result, 16, 32));
1272 			});
1273 
1274 		}
1275 
1276 		res = SCSI_SCAN_TARGET_PRESENT;
1277 		goto out_free_result;
1278 	}
1279 
1280 	/*
1281 	 * Some targets may set slight variations of PQ and PDT to signal
1282 	 * that no LUN is present, so don't add sdev in these cases.
1283 	 * Two specific examples are:
1284 	 * 1) NetApp targets: return PQ=1, PDT=0x1f
1285 	 * 2) USB UFI: returns PDT=0x1f, with the PQ bits being "reserved"
1286 	 *    in the UFI 1.0 spec (we cannot rely on reserved bits).
1287 	 *
1288 	 * References:
1289 	 * 1) SCSI SPC-3, pp. 145-146
1290 	 * PQ=1: "A peripheral device having the specified peripheral
1291 	 * device type is not connected to this logical unit. However, the
1292 	 * device server is capable of supporting the specified peripheral
1293 	 * device type on this logical unit."
1294 	 * PDT=0x1f: "Unknown or no device type"
1295 	 * 2) USB UFI 1.0, p. 20
1296 	 * PDT=00h Direct-access device (floppy)
1297 	 * PDT=1Fh none (no FDD connected to the requested logical unit)
1298 	 */
1299 	if (((result[0] >> 5) == 1 || starget->pdt_1f_for_no_lun) &&
1300 	    (result[0] & 0x1f) == 0x1f &&
1301 	    !scsi_is_wlun(lun)) {
1302 		SCSI_LOG_SCAN_BUS(3, sdev_printk(KERN_INFO, sdev,
1303 					"scsi scan: peripheral device type"
1304 					" of 31, no device added\n"));
1305 		res = SCSI_SCAN_TARGET_PRESENT;
1306 		goto out_free_result;
1307 	}
1308 
1309 	res = scsi_add_lun(sdev, result, &bflags, shost->async_scan);
1310 	if (res == SCSI_SCAN_LUN_PRESENT) {
1311 		if (bflags & BLIST_KEY) {
1312 			sdev->lockable = 0;
1313 			scsi_unlock_floptical(sdev, result);
1314 		}
1315 	}
1316 
1317  out_free_result:
1318 	kfree(result);
1319  out_free_sdev:
1320 	if (res == SCSI_SCAN_LUN_PRESENT) {
1321 		if (sdevp) {
1322 			if (scsi_device_get(sdev) == 0) {
1323 				*sdevp = sdev;
1324 			} else {
1325 				__scsi_remove_device(sdev);
1326 				res = SCSI_SCAN_NO_RESPONSE;
1327 			}
1328 		}
1329 	} else
1330 		__scsi_remove_device(sdev);
1331  out:
1332 	return res;
1333 }
1334 
1335 /**
1336  * scsi_sequential_lun_scan - sequentially scan a SCSI target
1337  * @starget:	pointer to target structure to scan
1338  * @bflags:	black/white list flag for LUN 0
1339  * @scsi_level: Which version of the standard does this device adhere to
1340  * @rescan:     passed to scsi_probe_add_lun()
1341  *
1342  * Description:
1343  *     Generally, scan from LUN 1 (LUN 0 is assumed to already have been
1344  *     scanned) to some maximum lun until a LUN is found with no device
1345  *     attached. Use the bflags to figure out any oddities.
1346  *
1347  *     Modifies sdevscan->lun.
1348  **/
1349 static void scsi_sequential_lun_scan(struct scsi_target *starget,
1350 				     blist_flags_t bflags, int scsi_level,
1351 				     enum scsi_scan_mode rescan)
1352 {
1353 	uint max_dev_lun;
1354 	u64 sparse_lun, lun;
1355 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
1356 
1357 	SCSI_LOG_SCAN_BUS(3, starget_printk(KERN_INFO, starget,
1358 		"scsi scan: Sequential scan\n"));
1359 
1360 	max_dev_lun = min(max_scsi_luns, shost->max_lun);
1361 	/*
1362 	 * If this device is known to support sparse multiple units,
1363 	 * override the other settings, and scan all of them. Normally,
1364 	 * SCSI-3 devices should be scanned via the REPORT LUNS.
1365 	 */
1366 	if (bflags & BLIST_SPARSELUN) {
1367 		max_dev_lun = shost->max_lun;
1368 		sparse_lun = 1;
1369 	} else
1370 		sparse_lun = 0;
1371 
1372 	/*
1373 	 * If less than SCSI_1_CCS, and no special lun scanning, stop
1374 	 * scanning; this matches 2.4 behaviour, but could just be a bug
1375 	 * (to continue scanning a SCSI_1_CCS device).
1376 	 *
1377 	 * This test is broken.  We might not have any device on lun0 for
1378 	 * a sparselun device, and if that's the case then how would we
1379 	 * know the real scsi_level, eh?  It might make sense to just not
1380 	 * scan any SCSI_1 device for non-0 luns, but that check would best
1381 	 * go into scsi_alloc_sdev() and just have it return null when asked
1382 	 * to alloc an sdev for lun > 0 on an already found SCSI_1 device.
1383 	 *
1384 	if ((sdevscan->scsi_level < SCSI_1_CCS) &&
1385 	    ((bflags & (BLIST_FORCELUN | BLIST_SPARSELUN | BLIST_MAX5LUN))
1386 	     == 0))
1387 		return;
1388 	 */
1389 	/*
1390 	 * If this device is known to support multiple units, override
1391 	 * the other settings, and scan all of them.
1392 	 */
1393 	if (bflags & BLIST_FORCELUN)
1394 		max_dev_lun = shost->max_lun;
1395 	/*
1396 	 * REGAL CDC-4X: avoid hang after LUN 4
1397 	 */
1398 	if (bflags & BLIST_MAX5LUN)
1399 		max_dev_lun = min(5U, max_dev_lun);
1400 	/*
1401 	 * Do not scan SCSI-2 or lower device past LUN 7, unless
1402 	 * BLIST_LARGELUN.
1403 	 */
1404 	if (scsi_level < SCSI_3 && !(bflags & BLIST_LARGELUN))
1405 		max_dev_lun = min(8U, max_dev_lun);
1406 	else
1407 		max_dev_lun = min(256U, max_dev_lun);
1408 
1409 	/*
1410 	 * We have already scanned LUN 0, so start at LUN 1. Keep scanning
1411 	 * until we reach the max, or no LUN is found and we are not
1412 	 * sparse_lun.
1413 	 */
1414 	for (lun = 1; lun < max_dev_lun; ++lun)
1415 		if ((scsi_probe_and_add_lun(starget, lun, NULL, NULL, rescan,
1416 					    NULL) != SCSI_SCAN_LUN_PRESENT) &&
1417 		    !sparse_lun)
1418 			return;
1419 }
1420 
1421 /**
1422  * scsi_report_lun_scan - Scan using SCSI REPORT LUN results
1423  * @starget: which target
1424  * @bflags: Zero or a mix of BLIST_NOLUN, BLIST_REPORTLUN2, or BLIST_NOREPORTLUN
1425  * @rescan: nonzero if we can skip code only needed on first scan
1426  *
1427  * Description:
1428  *   Fast scanning for modern (SCSI-3) devices by sending a REPORT LUN command.
1429  *   Scan the resulting list of LUNs by calling scsi_probe_and_add_lun.
1430  *
1431  *   If BLINK_REPORTLUN2 is set, scan a target that supports more than 8
1432  *   LUNs even if it's older than SCSI-3.
1433  *   If BLIST_NOREPORTLUN is set, return 1 always.
1434  *   If BLIST_NOLUN is set, return 0 always.
1435  *   If starget->no_report_luns is set, return 1 always.
1436  *
1437  * Return:
1438  *     0: scan completed (or no memory, so further scanning is futile)
1439  *     1: could not scan with REPORT LUN
1440  **/
1441 static int scsi_report_lun_scan(struct scsi_target *starget, blist_flags_t bflags,
1442 				enum scsi_scan_mode rescan)
1443 {
1444 	unsigned char scsi_cmd[MAX_COMMAND_SIZE];
1445 	unsigned int length;
1446 	u64 lun;
1447 	unsigned int num_luns;
1448 	int result;
1449 	struct scsi_lun *lunp, *lun_data;
1450 	struct scsi_device *sdev;
1451 	struct Scsi_Host *shost = dev_to_shost(&starget->dev);
1452 	struct scsi_failure failure_defs[] = {
1453 		{
1454 			.sense = UNIT_ATTENTION,
1455 			.asc = SCMD_FAILURE_ASC_ANY,
1456 			.ascq = SCMD_FAILURE_ASCQ_ANY,
1457 			.result = SAM_STAT_CHECK_CONDITION,
1458 		},
1459 		/* Fail all CCs except the UA above */
1460 		{
1461 			.sense = SCMD_FAILURE_SENSE_ANY,
1462 			.result = SAM_STAT_CHECK_CONDITION,
1463 		},
1464 		/* Retry any other errors not listed above */
1465 		{
1466 			.result = SCMD_FAILURE_RESULT_ANY,
1467 		},
1468 		{}
1469 	};
1470 	struct scsi_failures failures = {
1471 		.total_allowed = 3,
1472 		.failure_definitions = failure_defs,
1473 	};
1474 	const struct scsi_exec_args exec_args = {
1475 		.failures = &failures,
1476 	};
1477 	int ret = 0;
1478 
1479 	/*
1480 	 * Only support SCSI-3 and up devices if BLIST_NOREPORTLUN is not set.
1481 	 * Also allow SCSI-2 if BLIST_REPORTLUN2 is set and host adapter does
1482 	 * support more than 8 LUNs.
1483 	 * Don't attempt if the target doesn't support REPORT LUNS.
1484 	 */
1485 	if (bflags & BLIST_NOREPORTLUN)
1486 		return 1;
1487 	if (starget->scsi_level < SCSI_2 &&
1488 	    starget->scsi_level != SCSI_UNKNOWN)
1489 		return 1;
1490 	if (starget->scsi_level < SCSI_3 &&
1491 	    (!(bflags & BLIST_REPORTLUN2) || shost->max_lun <= 8))
1492 		return 1;
1493 	if (bflags & BLIST_NOLUN)
1494 		return 0;
1495 	if (starget->no_report_luns)
1496 		return 1;
1497 
1498 	if (!(sdev = scsi_device_lookup_by_target(starget, 0))) {
1499 		sdev = scsi_alloc_sdev(starget, 0, NULL);
1500 		if (!sdev)
1501 			return 0;
1502 		if (scsi_device_get(sdev)) {
1503 			__scsi_remove_device(sdev);
1504 			return 0;
1505 		}
1506 	}
1507 
1508 	/*
1509 	 * Allocate enough to hold the header (the same size as one scsi_lun)
1510 	 * plus the number of luns we are requesting.  511 was the default
1511 	 * value of the now removed max_report_luns parameter.
1512 	 */
1513 	length = (511 + 1) * sizeof(struct scsi_lun);
1514 retry:
1515 	lun_data = kmalloc(length, GFP_KERNEL);
1516 	if (!lun_data) {
1517 		printk(ALLOC_FAILURE_MSG, __func__);
1518 		goto out;
1519 	}
1520 
1521 	scsi_cmd[0] = REPORT_LUNS;
1522 
1523 	/*
1524 	 * bytes 1 - 5: reserved, set to zero.
1525 	 */
1526 	memset(&scsi_cmd[1], 0, 5);
1527 
1528 	/*
1529 	 * bytes 6 - 9: length of the command.
1530 	 */
1531 	put_unaligned_be32(length, &scsi_cmd[6]);
1532 
1533 	scsi_cmd[10] = 0;	/* reserved */
1534 	scsi_cmd[11] = 0;	/* control */
1535 
1536 	/*
1537 	 * We can get a UNIT ATTENTION, for example a power on/reset, so
1538 	 * retry a few times (like sd.c does for TEST UNIT READY).
1539 	 * Experience shows some combinations of adapter/devices get at
1540 	 * least two power on/resets.
1541 	 *
1542 	 * Illegal requests (for devices that do not support REPORT LUNS)
1543 	 * should come through as a check condition, and will not generate
1544 	 * a retry.
1545 	 */
1546 	scsi_failures_reset_retries(&failures);
1547 
1548 	SCSI_LOG_SCAN_BUS(3, sdev_printk (KERN_INFO, sdev,
1549 			  "scsi scan: Sending REPORT LUNS\n"));
1550 
1551 	result = scsi_execute_cmd(sdev, scsi_cmd, REQ_OP_DRV_IN, lun_data,
1552 				  length, SCSI_REPORT_LUNS_TIMEOUT, 3,
1553 				  &exec_args);
1554 
1555 	SCSI_LOG_SCAN_BUS(3, sdev_printk (KERN_INFO, sdev,
1556 			  "scsi scan: REPORT LUNS  %s result 0x%x\n",
1557 			  result ?  "failed" : "successful", result));
1558 	if (result) {
1559 		/*
1560 		 * The device probably does not support a REPORT LUN command
1561 		 */
1562 		ret = 1;
1563 		goto out_err;
1564 	}
1565 
1566 	/*
1567 	 * Get the length from the first four bytes of lun_data.
1568 	 */
1569 	if (get_unaligned_be32(lun_data->scsi_lun) +
1570 	    sizeof(struct scsi_lun) > length) {
1571 		length = get_unaligned_be32(lun_data->scsi_lun) +
1572 			 sizeof(struct scsi_lun);
1573 		kfree(lun_data);
1574 		goto retry;
1575 	}
1576 	length = get_unaligned_be32(lun_data->scsi_lun);
1577 
1578 	num_luns = (length / sizeof(struct scsi_lun));
1579 
1580 	SCSI_LOG_SCAN_BUS(3, sdev_printk (KERN_INFO, sdev,
1581 		"scsi scan: REPORT LUN scan\n"));
1582 
1583 	/*
1584 	 * Scan the luns in lun_data. The entry at offset 0 is really
1585 	 * the header, so start at 1 and go up to and including num_luns.
1586 	 */
1587 	for (lunp = &lun_data[1]; lunp <= &lun_data[num_luns]; lunp++) {
1588 		lun = scsilun_to_int(lunp);
1589 
1590 		if (lun > sdev->host->max_lun) {
1591 			sdev_printk(KERN_WARNING, sdev,
1592 				    "lun%llu has a LUN larger than"
1593 				    " allowed by the host adapter\n", lun);
1594 		} else {
1595 			int res;
1596 
1597 			res = scsi_probe_and_add_lun(starget,
1598 				lun, NULL, NULL, rescan, NULL);
1599 			if (res == SCSI_SCAN_NO_RESPONSE) {
1600 				/*
1601 				 * Got some results, but now none, abort.
1602 				 */
1603 				sdev_printk(KERN_ERR, sdev,
1604 					"Unexpected response"
1605 					" from lun %llu while scanning, scan"
1606 					" aborted\n", (unsigned long long)lun);
1607 				break;
1608 			}
1609 		}
1610 	}
1611 
1612  out_err:
1613 	kfree(lun_data);
1614  out:
1615 	if (scsi_device_created(sdev))
1616 		/*
1617 		 * the sdev we used didn't appear in the report luns scan
1618 		 */
1619 		__scsi_remove_device(sdev);
1620 	scsi_device_put(sdev);
1621 	return ret;
1622 }
1623 
1624 struct scsi_device *__scsi_add_device(struct Scsi_Host *shost, uint channel,
1625 				      uint id, u64 lun, void *hostdata)
1626 {
1627 	struct scsi_device *sdev = ERR_PTR(-ENODEV);
1628 	struct device *parent = &shost->shost_gendev;
1629 	struct scsi_target *starget;
1630 
1631 	if (strncmp(scsi_scan_type, "none", 4) == 0)
1632 		return ERR_PTR(-ENODEV);
1633 
1634 	starget = scsi_alloc_target(parent, channel, id);
1635 	if (!starget)
1636 		return ERR_PTR(-ENOMEM);
1637 	scsi_autopm_get_target(starget);
1638 
1639 	mutex_lock(&shost->scan_mutex);
1640 	if (!shost->async_scan)
1641 		scsi_complete_async_scans();
1642 
1643 	if (scsi_host_scan_allowed(shost) && scsi_autopm_get_host(shost) == 0) {
1644 		scsi_probe_and_add_lun(starget, lun, NULL, &sdev,
1645 				       SCSI_SCAN_RESCAN, hostdata);
1646 		scsi_autopm_put_host(shost);
1647 	}
1648 	mutex_unlock(&shost->scan_mutex);
1649 	scsi_autopm_put_target(starget);
1650 	/*
1651 	 * paired with scsi_alloc_target().  Target will be destroyed unless
1652 	 * scsi_probe_and_add_lun made an underlying device visible
1653 	 */
1654 	scsi_target_reap(starget);
1655 	put_device(&starget->dev);
1656 
1657 	return sdev;
1658 }
1659 EXPORT_SYMBOL(__scsi_add_device);
1660 
1661 /**
1662  * scsi_add_device - creates a new SCSI (LU) instance
1663  * @host: the &Scsi_Host instance where the device is located
1664  * @channel: target channel number (rarely other than %0)
1665  * @target: target id number
1666  * @lun: LUN of target device
1667  *
1668  * Probe for a specific LUN and add it if found.
1669  *
1670  * Notes: This call is usually performed internally during a SCSI
1671  * bus scan when an HBA is added (i.e. scsi_scan_host()). So it
1672  * should only be called if the HBA becomes aware of a new SCSI
1673  * device (LU) after scsi_scan_host() has completed. If successful
1674  * this call can lead to sdev_init() and sdev_configure() callbacks
1675  * into the LLD.
1676  *
1677  * Return: %0 on success or negative error code on failure
1678  */
1679 int scsi_add_device(struct Scsi_Host *host, uint channel,
1680 		    uint target, u64 lun)
1681 {
1682 	struct scsi_device *sdev =
1683 		__scsi_add_device(host, channel, target, lun, NULL);
1684 	if (IS_ERR(sdev))
1685 		return PTR_ERR(sdev);
1686 
1687 	scsi_device_put(sdev);
1688 	return 0;
1689 }
1690 EXPORT_SYMBOL(scsi_add_device);
1691 
1692 int scsi_resume_device(struct scsi_device *sdev)
1693 {
1694 	struct device *dev = &sdev->sdev_gendev;
1695 	int ret = 0;
1696 
1697 	device_lock(dev);
1698 
1699 	/*
1700 	 * Bail out if the device or its queue are not running. Otherwise,
1701 	 * the rescan may block waiting for commands to be executed, with us
1702 	 * holding the device lock. This can result in a potential deadlock
1703 	 * in the power management core code when system resume is on-going.
1704 	 */
1705 	if (sdev->sdev_state != SDEV_RUNNING ||
1706 	    blk_queue_pm_only(sdev->request_queue)) {
1707 		ret = -EWOULDBLOCK;
1708 		goto unlock;
1709 	}
1710 
1711 	if (dev->driver && try_module_get(dev->driver->owner)) {
1712 		struct scsi_driver *drv = to_scsi_driver(dev->driver);
1713 
1714 		if (drv->resume)
1715 			ret = drv->resume(dev);
1716 		module_put(dev->driver->owner);
1717 	}
1718 
1719 unlock:
1720 	device_unlock(dev);
1721 
1722 	return ret;
1723 }
1724 EXPORT_SYMBOL(scsi_resume_device);
1725 
1726 int scsi_rescan_device(struct scsi_device *sdev)
1727 {
1728 	struct device *dev = &sdev->sdev_gendev;
1729 	int ret = 0;
1730 
1731 	device_lock(dev);
1732 
1733 	/*
1734 	 * Bail out if the device or its queue are not running. Otherwise,
1735 	 * the rescan may block waiting for commands to be executed, with us
1736 	 * holding the device lock. This can result in a potential deadlock
1737 	 * in the power management core code when system resume is on-going.
1738 	 */
1739 	if (sdev->sdev_state != SDEV_RUNNING ||
1740 	    blk_queue_pm_only(sdev->request_queue)) {
1741 		ret = -EWOULDBLOCK;
1742 		goto unlock;
1743 	}
1744 
1745 	scsi_attach_vpd(sdev);
1746 	scsi_cdl_check(sdev);
1747 
1748 	if (sdev->handler && sdev->handler->rescan)
1749 		sdev->handler->rescan(sdev);
1750 
1751 	if (dev->driver && try_module_get(dev->driver->owner)) {
1752 		struct scsi_driver *drv = to_scsi_driver(dev->driver);
1753 
1754 		if (drv->rescan)
1755 			drv->rescan(dev);
1756 		module_put(dev->driver->owner);
1757 	}
1758 
1759 unlock:
1760 	device_unlock(dev);
1761 
1762 	return ret;
1763 }
1764 EXPORT_SYMBOL(scsi_rescan_device);
1765 
1766 static void __scsi_scan_target(struct device *parent, unsigned int channel,
1767 		unsigned int id, u64 lun, enum scsi_scan_mode rescan)
1768 {
1769 	struct Scsi_Host *shost = dev_to_shost(parent);
1770 	blist_flags_t bflags = 0;
1771 	int res;
1772 	struct scsi_target *starget;
1773 
1774 	if (shost->this_id == id)
1775 		/*
1776 		 * Don't scan the host adapter
1777 		 */
1778 		return;
1779 
1780 	starget = scsi_alloc_target(parent, channel, id);
1781 	if (!starget)
1782 		return;
1783 	scsi_autopm_get_target(starget);
1784 
1785 	if (lun != SCAN_WILD_CARD) {
1786 		/*
1787 		 * Scan for a specific host/chan/id/lun.
1788 		 */
1789 		scsi_probe_and_add_lun(starget, lun, NULL, NULL, rescan, NULL);
1790 		goto out_reap;
1791 	}
1792 
1793 	/*
1794 	 * Scan LUN 0, if there is some response, scan further. Ideally, we
1795 	 * would not configure LUN 0 until all LUNs are scanned.
1796 	 */
1797 	res = scsi_probe_and_add_lun(starget, 0, &bflags, NULL, rescan, NULL);
1798 	if (res == SCSI_SCAN_LUN_PRESENT || res == SCSI_SCAN_TARGET_PRESENT) {
1799 		if (scsi_report_lun_scan(starget, bflags, rescan) != 0)
1800 			/*
1801 			 * The REPORT LUN did not scan the target,
1802 			 * do a sequential scan.
1803 			 */
1804 			scsi_sequential_lun_scan(starget, bflags,
1805 						 starget->scsi_level, rescan);
1806 	}
1807 
1808  out_reap:
1809 	scsi_autopm_put_target(starget);
1810 	/*
1811 	 * paired with scsi_alloc_target(): determine if the target has
1812 	 * any children at all and if not, nuke it
1813 	 */
1814 	scsi_target_reap(starget);
1815 
1816 	put_device(&starget->dev);
1817 }
1818 
1819 /**
1820  * scsi_scan_target - scan a target id, possibly including all LUNs on the target.
1821  * @parent:	host to scan
1822  * @channel:	channel to scan
1823  * @id:		target id to scan
1824  * @lun:	Specific LUN to scan or SCAN_WILD_CARD
1825  * @rescan:	passed to LUN scanning routines; SCSI_SCAN_INITIAL for
1826  *              no rescan, SCSI_SCAN_RESCAN to rescan existing LUNs,
1827  *              and SCSI_SCAN_MANUAL to force scanning even if
1828  *              'scan=manual' is set.
1829  *
1830  * Description:
1831  *     Scan the target id on @parent, @channel, and @id. Scan at least LUN 0,
1832  *     and possibly all LUNs on the target id.
1833  *
1834  *     First try a REPORT LUN scan, if that does not scan the target, do a
1835  *     sequential scan of LUNs on the target id.
1836  **/
1837 void scsi_scan_target(struct device *parent, unsigned int channel,
1838 		      unsigned int id, u64 lun, enum scsi_scan_mode rescan)
1839 {
1840 	struct Scsi_Host *shost = dev_to_shost(parent);
1841 
1842 	if (strncmp(scsi_scan_type, "none", 4) == 0)
1843 		return;
1844 
1845 	if (rescan != SCSI_SCAN_MANUAL &&
1846 	    strncmp(scsi_scan_type, "manual", 6) == 0)
1847 		return;
1848 
1849 	mutex_lock(&shost->scan_mutex);
1850 	if (!shost->async_scan)
1851 		scsi_complete_async_scans();
1852 
1853 	if (scsi_host_scan_allowed(shost) && scsi_autopm_get_host(shost) == 0) {
1854 		__scsi_scan_target(parent, channel, id, lun, rescan);
1855 		scsi_autopm_put_host(shost);
1856 	}
1857 	mutex_unlock(&shost->scan_mutex);
1858 }
1859 EXPORT_SYMBOL(scsi_scan_target);
1860 
1861 static void scsi_scan_channel(struct Scsi_Host *shost, unsigned int channel,
1862 			      unsigned int id, u64 lun,
1863 			      enum scsi_scan_mode rescan)
1864 {
1865 	uint order_id;
1866 
1867 	if (id == SCAN_WILD_CARD)
1868 		for (id = 0; id < shost->max_id; ++id) {
1869 			/*
1870 			 * XXX adapter drivers when possible (FCP, iSCSI)
1871 			 * could modify max_id to match the current max,
1872 			 * not the absolute max.
1873 			 *
1874 			 * XXX add a shost id iterator, so for example,
1875 			 * the FC ID can be the same as a target id
1876 			 * without a huge overhead of sparse id's.
1877 			 */
1878 			if (shost->reverse_ordering)
1879 				/*
1880 				 * Scan from high to low id.
1881 				 */
1882 				order_id = shost->max_id - id - 1;
1883 			else
1884 				order_id = id;
1885 			__scsi_scan_target(&shost->shost_gendev, channel,
1886 					order_id, lun, rescan);
1887 		}
1888 	else
1889 		__scsi_scan_target(&shost->shost_gendev, channel,
1890 				id, lun, rescan);
1891 }
1892 
1893 int scsi_scan_host_selected(struct Scsi_Host *shost, unsigned int channel,
1894 			    unsigned int id, u64 lun,
1895 			    enum scsi_scan_mode rescan)
1896 {
1897 	SCSI_LOG_SCAN_BUS(3, shost_printk (KERN_INFO, shost,
1898 		"%s: <%u:%u:%llu>\n",
1899 		__func__, channel, id, lun));
1900 
1901 	if (((channel != SCAN_WILD_CARD) && (channel > shost->max_channel)) ||
1902 	    ((id != SCAN_WILD_CARD) && (id >= shost->max_id)) ||
1903 	    ((lun != SCAN_WILD_CARD) && (lun >= shost->max_lun)))
1904 		return -EINVAL;
1905 
1906 	mutex_lock(&shost->scan_mutex);
1907 	if (!shost->async_scan)
1908 		scsi_complete_async_scans();
1909 
1910 	if (scsi_host_scan_allowed(shost) && scsi_autopm_get_host(shost) == 0) {
1911 		if (channel == SCAN_WILD_CARD)
1912 			for (channel = 0; channel <= shost->max_channel;
1913 			     channel++)
1914 				scsi_scan_channel(shost, channel, id, lun,
1915 						  rescan);
1916 		else
1917 			scsi_scan_channel(shost, channel, id, lun, rescan);
1918 		scsi_autopm_put_host(shost);
1919 	}
1920 	mutex_unlock(&shost->scan_mutex);
1921 
1922 	return 0;
1923 }
1924 
1925 static void scsi_sysfs_add_devices(struct Scsi_Host *shost)
1926 {
1927 	struct scsi_device *sdev;
1928 	shost_for_each_device(sdev, shost) {
1929 		/* target removed before the device could be added */
1930 		if (sdev->sdev_state == SDEV_DEL)
1931 			continue;
1932 		/* If device is already visible, skip adding it to sysfs */
1933 		if (sdev->is_visible)
1934 			continue;
1935 		if (!scsi_host_scan_allowed(shost) ||
1936 		    scsi_sysfs_add_sdev(sdev) != 0)
1937 			__scsi_remove_device(sdev);
1938 	}
1939 }
1940 
1941 /**
1942  * scsi_prep_async_scan - prepare for an async scan
1943  * @shost: the host which will be scanned
1944  * Returns: a cookie to be passed to scsi_finish_async_scan()
1945  *
1946  * Tells the midlayer this host is going to do an asynchronous scan.
1947  * It reserves the host's position in the scanning list and ensures
1948  * that other asynchronous scans started after this one won't affect the
1949  * ordering of the discovered devices.
1950  */
1951 static struct async_scan_data *scsi_prep_async_scan(struct Scsi_Host *shost)
1952 {
1953 	struct async_scan_data *data = NULL;
1954 
1955 	if (strncmp(scsi_scan_type, "sync", 4) == 0)
1956 		return NULL;
1957 
1958 	mutex_lock(&shost->scan_mutex);
1959 	if (shost->async_scan) {
1960 		shost_printk(KERN_DEBUG, shost, "%s called twice\n", __func__);
1961 		goto err;
1962 	}
1963 
1964 	data = kmalloc_obj(*data);
1965 	if (!data)
1966 		goto err;
1967 	data->shost = scsi_host_get(shost);
1968 	if (!data->shost)
1969 		goto err;
1970 	init_completion(&data->prev_finished);
1971 
1972 	shost->async_scan = true;
1973 	mutex_unlock(&shost->scan_mutex);
1974 
1975 	spin_lock(&async_scan_lock);
1976 	if (list_empty(&scanning_hosts))
1977 		complete(&data->prev_finished);
1978 	list_add_tail(&data->list, &scanning_hosts);
1979 	spin_unlock(&async_scan_lock);
1980 
1981 	return data;
1982 
1983  err:
1984 	mutex_unlock(&shost->scan_mutex);
1985 	kfree(data);
1986 	return NULL;
1987 }
1988 
1989 /**
1990  * scsi_finish_async_scan - asynchronous scan has finished
1991  * @data: cookie returned from earlier call to scsi_prep_async_scan()
1992  *
1993  * All the devices currently attached to this host have been found.
1994  * This function announces all the devices it has found to the rest
1995  * of the system.
1996  */
1997 static void scsi_finish_async_scan(struct async_scan_data *data)
1998 {
1999 	struct Scsi_Host *shost;
2000 
2001 	if (!data)
2002 		return;
2003 
2004 	shost = data->shost;
2005 
2006 	mutex_lock(&shost->scan_mutex);
2007 
2008 	if (!shost->async_scan) {
2009 		shost_printk(KERN_INFO, shost, "%s called twice\n", __func__);
2010 		dump_stack();
2011 		mutex_unlock(&shost->scan_mutex);
2012 		return;
2013 	}
2014 
2015 	wait_for_completion(&data->prev_finished);
2016 
2017 	scsi_sysfs_add_devices(shost);
2018 
2019 	shost->async_scan = false;
2020 
2021 	mutex_unlock(&shost->scan_mutex);
2022 
2023 	spin_lock(&async_scan_lock);
2024 	list_del(&data->list);
2025 	if (!list_empty(&scanning_hosts)) {
2026 		struct async_scan_data *next = list_entry(scanning_hosts.next,
2027 				struct async_scan_data, list);
2028 		complete(&next->prev_finished);
2029 	}
2030 	spin_unlock(&async_scan_lock);
2031 
2032 	scsi_autopm_put_host(shost);
2033 	scsi_host_put(shost);
2034 	kfree(data);
2035 }
2036 
2037 static void do_scsi_scan_host(struct Scsi_Host *shost)
2038 {
2039 	if (shost->hostt->scan_finished) {
2040 		unsigned long start = jiffies;
2041 		if (shost->hostt->scan_start)
2042 			shost->hostt->scan_start(shost);
2043 
2044 		while (!shost->hostt->scan_finished(shost, jiffies - start))
2045 			msleep(10);
2046 	} else {
2047 		scsi_scan_host_selected(shost, SCAN_WILD_CARD, SCAN_WILD_CARD,
2048 				SCAN_WILD_CARD, SCSI_SCAN_INITIAL);
2049 	}
2050 }
2051 
2052 static void do_scan_async(void *_data, async_cookie_t c)
2053 {
2054 	struct async_scan_data *data = _data;
2055 	struct Scsi_Host *shost = data->shost;
2056 
2057 	do_scsi_scan_host(shost);
2058 	scsi_finish_async_scan(data);
2059 }
2060 
2061 /**
2062  * scsi_scan_host - scan the given adapter
2063  * @shost:	adapter to scan
2064  *
2065  * Notes: Should be called after scsi_add_host()
2066  **/
2067 void scsi_scan_host(struct Scsi_Host *shost)
2068 {
2069 	struct async_scan_data *data;
2070 
2071 	if (strncmp(scsi_scan_type, "none", 4) == 0 ||
2072 	    strncmp(scsi_scan_type, "manual", 6) == 0)
2073 		return;
2074 	if (scsi_autopm_get_host(shost) < 0)
2075 		return;
2076 
2077 	data = scsi_prep_async_scan(shost);
2078 	if (!data) {
2079 		do_scsi_scan_host(shost);
2080 		scsi_autopm_put_host(shost);
2081 		return;
2082 	}
2083 
2084 	/* register with the async subsystem so wait_for_device_probe()
2085 	 * will flush this work
2086 	 */
2087 	async_schedule(do_scan_async, data);
2088 
2089 	/* scsi_autopm_put_host(shost) is called in scsi_finish_async_scan() */
2090 }
2091 EXPORT_SYMBOL(scsi_scan_host);
2092 
2093 void scsi_forget_host(struct Scsi_Host *shost)
2094 {
2095 	struct scsi_device *sdev;
2096 	unsigned long flags;
2097 
2098  restart:
2099 	spin_lock_irqsave(shost->host_lock, flags);
2100 	list_for_each_entry(sdev, &shost->__devices, siblings) {
2101 		if (scsi_device_is_pseudo_dev(sdev) ||
2102 		    sdev->sdev_state == SDEV_DEL)
2103 			continue;
2104 		spin_unlock_irqrestore(shost->host_lock, flags);
2105 		__scsi_remove_device(sdev);
2106 		goto restart;
2107 	}
2108 	spin_unlock_irqrestore(shost->host_lock, flags);
2109 
2110 	/*
2111 	 * Remove the pseudo device last since it may be needed during removal
2112 	 * of other SCSI devices.
2113 	 */
2114 	if (shost->pseudo_sdev)
2115 		__scsi_remove_device(shost->pseudo_sdev);
2116 }
2117 
2118 /**
2119  * scsi_get_pseudo_sdev() - Attach a pseudo SCSI device to a SCSI host
2120  * @shost: Host that needs a pseudo SCSI device
2121  *
2122  * Lock status: None assumed.
2123  *
2124  * Returns:     The scsi_device or NULL
2125  *
2126  * Notes:
2127  *	Attach a single scsi_device to the Scsi_Host. The primary aim for this
2128  *	device is to serve as a container from which SCSI commands can be
2129  *	allocated. Each SCSI command will carry a command tag allocated by the
2130  *	block layer. These SCSI commands can be used by the LLDD to send
2131  *	internal or passthrough commands without having to manage tag allocation
2132  *	inside the LLDD.
2133  */
2134 struct scsi_device *scsi_get_pseudo_sdev(struct Scsi_Host *shost)
2135 {
2136 	struct scsi_device *sdev = NULL;
2137 	struct scsi_target *starget;
2138 
2139 	guard(mutex)(&shost->scan_mutex);
2140 
2141 	if (!scsi_host_scan_allowed(shost))
2142 		goto out;
2143 
2144 	starget = scsi_alloc_target(&shost->shost_gendev, 0, shost->max_id);
2145 	if (!starget)
2146 		goto out;
2147 
2148 	sdev = scsi_alloc_sdev(starget, U64_MAX, NULL);
2149 	if (!sdev) {
2150 		scsi_target_reap(starget);
2151 		goto put_target;
2152 	}
2153 
2154 	sdev->borken = 0;
2155 
2156 put_target:
2157 	/* See also the get_device(dev) call in scsi_alloc_target(). */
2158 	put_device(&starget->dev);
2159 
2160 out:
2161 	return sdev;
2162 }
2163