xref: /linux/drivers/s390/block/dasd.c (revision 25cdc1f63227a1ea69a1ec823a8a860e33299169)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
4  *		    Horst Hummel <Horst.Hummel@de.ibm.com>
5  *		    Carsten Otte <Cotte@de.ibm.com>
6  *		    Martin Schwidefsky <schwidefsky@de.ibm.com>
7  * Bugreports.to..: <Linux390@de.ibm.com>
8  * Copyright IBM Corp. 1999, 2009
9  */
10 
11 #include <linux/export.h>
12 #include <linux/kmod.h>
13 #include <linux/init.h>
14 #include <linux/interrupt.h>
15 #include <linux/ctype.h>
16 #include <linux/major.h>
17 #include <linux/slab.h>
18 #include <linux/hdreg.h>
19 #include <linux/async.h>
20 #include <linux/mutex.h>
21 #include <linux/debugfs.h>
22 #include <linux/seq_file.h>
23 #include <linux/vmalloc.h>
24 #include <linux/delay.h>
25 
26 #include <asm/machine.h>
27 #include <asm/ccwdev.h>
28 #include <asm/ebcdic.h>
29 #include <asm/idals.h>
30 #include <asm/itcw.h>
31 #include <asm/diag.h>
32 
33 #include "dasd_int.h"
34 /*
35  * SECTION: Constant definitions to be used within this file
36  */
37 #define DASD_CHANQ_MAX_SIZE 4
38 
39 #define DASD_DIAG_MOD		"dasd_diag_mod"
40 
41 /*
42  * SECTION: exported variables of dasd.c
43  */
44 debug_info_t *dasd_debug_area;
45 EXPORT_SYMBOL(dasd_debug_area);
46 static struct dentry *dasd_debugfs_root_entry;
47 struct dasd_discipline *dasd_diag_discipline_pointer;
48 EXPORT_SYMBOL(dasd_diag_discipline_pointer);
49 void dasd_int_handler(struct ccw_device *, unsigned long, struct irb *);
50 
51 MODULE_AUTHOR("Holger Smolinski <Holger.Smolinski@de.ibm.com>");
52 MODULE_DESCRIPTION("Linux on S/390 DASD device driver,"
53 		   " Copyright IBM Corp. 2000");
54 MODULE_LICENSE("GPL");
55 
56 /*
57  * SECTION: prototypes for static functions of dasd.c
58  */
59 static int dasd_flush_block_queue(struct dasd_block *);
60 static void dasd_device_tasklet(unsigned long);
61 static void dasd_block_tasklet(unsigned long);
62 static void do_kick_device(struct work_struct *);
63 static void do_reload_device(struct work_struct *);
64 static void do_requeue_requests(struct work_struct *);
65 static void dasd_return_cqr_cb(struct dasd_ccw_req *, void *);
66 static void dasd_device_timeout(struct timer_list *);
67 static void dasd_block_timeout(struct timer_list *);
68 static void __dasd_process_erp(struct dasd_device *, struct dasd_ccw_req *);
69 static void dasd_profile_init(struct dasd_profile *, struct dentry *);
70 static void dasd_profile_exit(struct dasd_profile *);
71 static void dasd_hosts_init(struct dentry *, struct dasd_device *);
72 static void dasd_hosts_exit(struct dasd_device *);
73 static int dasd_handle_autoquiesce(struct dasd_device *, struct dasd_ccw_req *,
74 				   unsigned int);
75 /*
76  * SECTION: Operations on the device structure.
77  */
78 static wait_queue_head_t dasd_init_waitq;
79 static wait_queue_head_t dasd_flush_wq;
80 static wait_queue_head_t generic_waitq;
81 static wait_queue_head_t shutdown_waitq;
82 
83 /*
84  * Allocate memory for a new device structure.
85  */
86 struct dasd_device *dasd_alloc_device(void)
87 {
88 	struct dasd_device *device;
89 
90 	device = kzalloc_obj(struct dasd_device);
91 	if (!device)
92 		return ERR_PTR(-ENOMEM);
93 
94 	/*
95 	 * Four pages: a full-track ITCW is roughly twice the size of a plain
96 	 * track-mode one, so this keeps two maximum-size requests in flight.
97 	 */
98 	device->ccw_mem = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, 2);
99 	if (!device->ccw_mem) {
100 		kfree(device);
101 		return ERR_PTR(-ENOMEM);
102 	}
103 	/* per-request track-filler buffers (R0 + count records) */
104 	device->fill_mem = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, 1);
105 	if (!device->fill_mem) {
106 		free_pages((unsigned long)device->ccw_mem, 2);
107 		kfree(device);
108 		return ERR_PTR(-ENOMEM);
109 	}
110 	/* Get one page for error recovery. */
111 	device->erp_mem = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
112 	if (!device->erp_mem) {
113 		free_pages((unsigned long)device->fill_mem, 1);
114 		free_pages((unsigned long)device->ccw_mem, 2);
115 		kfree(device);
116 		return ERR_PTR(-ENOMEM);
117 	}
118 	/* sized like ccw_chunks: two max-size NRF format requests in flight */
119 	device->ese_mem = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, 2);
120 	if (!device->ese_mem) {
121 		free_page((unsigned long)device->erp_mem);
122 		free_pages((unsigned long)device->fill_mem, 1);
123 		free_pages((unsigned long)device->ccw_mem, 2);
124 		kfree(device);
125 		return ERR_PTR(-ENOMEM);
126 	}
127 	device->nulldata = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
128 	if (!device->nulldata) {
129 		free_page((unsigned long)device->erp_mem);
130 		free_pages((unsigned long)device->fill_mem, 1);
131 		free_pages((unsigned long)device->ccw_mem, 2);
132 		free_pages((unsigned long)device->ese_mem, 2);
133 		kfree(device);
134 		return ERR_PTR(-ENOMEM);
135 	}
136 
137 	dasd_init_chunklist(&device->ccw_chunks, device->ccw_mem, PAGE_SIZE * 4);
138 	dasd_init_chunklist(&device->fill_chunks, device->fill_mem, PAGE_SIZE * 2);
139 	dasd_init_chunklist(&device->erp_chunks, device->erp_mem, PAGE_SIZE);
140 	dasd_init_chunklist(&device->ese_chunks, device->ese_mem, PAGE_SIZE * 4);
141 	spin_lock_init(&device->mem_lock);
142 	atomic_set(&device->tasklet_scheduled, 0);
143 	tasklet_init(&device->tasklet, dasd_device_tasklet,
144 		     (unsigned long) device);
145 	INIT_LIST_HEAD(&device->ccw_queue);
146 	timer_setup(&device->timer, dasd_device_timeout, 0);
147 	INIT_WORK(&device->kick_work, do_kick_device);
148 	INIT_WORK(&device->reload_device, do_reload_device);
149 	INIT_WORK(&device->requeue_requests, do_requeue_requests);
150 	device->state = DASD_STATE_NEW;
151 	device->target = DASD_STATE_NEW;
152 	mutex_init(&device->state_mutex);
153 	spin_lock_init(&device->profile.lock);
154 	return device;
155 }
156 
157 /*
158  * Free memory of a device structure.
159  */
160 void dasd_free_device(struct dasd_device *device)
161 {
162 	kfree(device->private);
163 	free_pages((unsigned long)device->ese_mem, 2);
164 	free_page((unsigned long)device->erp_mem);
165 	free_pages((unsigned long)device->fill_mem, 1);
166 	free_pages((unsigned long)device->ccw_mem, 2);
167 	free_page((unsigned long)device->nulldata);
168 	kfree(device);
169 }
170 
171 /*
172  * Allocate memory for a new device structure.
173  */
174 struct dasd_block *dasd_alloc_block(void)
175 {
176 	struct dasd_block *block;
177 
178 	block = kzalloc_obj(*block, GFP_ATOMIC);
179 	if (!block)
180 		return ERR_PTR(-ENOMEM);
181 	/* open_count = 0 means device online but not in use */
182 	atomic_set(&block->open_count, -1);
183 
184 	atomic_set(&block->tasklet_scheduled, 0);
185 	tasklet_init(&block->tasklet, dasd_block_tasklet,
186 		     (unsigned long) block);
187 	INIT_LIST_HEAD(&block->ccw_queue);
188 	spin_lock_init(&block->queue_lock);
189 	INIT_LIST_HEAD(&block->format_list);
190 	spin_lock_init(&block->format_lock);
191 	INIT_LIST_HEAD(&block->ese_staging);
192 	spin_lock_init(&block->ese_lock);
193 	timer_setup(&block->timer, dasd_block_timeout, 0);
194 	spin_lock_init(&block->profile.lock);
195 
196 	return block;
197 }
198 EXPORT_SYMBOL_GPL(dasd_alloc_block);
199 
200 /*
201  * Free memory of a device structure.
202  */
203 void dasd_free_block(struct dasd_block *block)
204 {
205 	kfree(block);
206 }
207 EXPORT_SYMBOL_GPL(dasd_free_block);
208 
209 /*
210  * Make a new device known to the system.
211  */
212 static int dasd_state_new_to_known(struct dasd_device *device)
213 {
214 	/*
215 	 * As long as the device is not in state DASD_STATE_NEW we want to
216 	 * keep the reference count > 0.
217 	 */
218 	dasd_get_device(device);
219 	device->state = DASD_STATE_KNOWN;
220 	return 0;
221 }
222 
223 /*
224  * Let the system forget about a device.
225  */
226 static int dasd_state_known_to_new(struct dasd_device *device)
227 {
228 	/* Disable extended error reporting for this device. */
229 	dasd_eer_disable(device);
230 	device->state = DASD_STATE_NEW;
231 
232 	/* Give up reference we took in dasd_state_new_to_known. */
233 	dasd_put_device(device);
234 	return 0;
235 }
236 
237 /*
238  * Request the irq line for the device.
239  */
240 static int dasd_state_known_to_basic(struct dasd_device *device)
241 {
242 	struct dasd_block *block = device->block;
243 	int rc = 0;
244 
245 	/* Allocate and register gendisk structure. */
246 	if (block) {
247 		rc = dasd_gendisk_alloc(block);
248 		if (rc)
249 			return rc;
250 		block->debugfs_dentry =
251 			debugfs_create_dir(block->gdp->disk_name,
252 					   dasd_debugfs_root_entry);
253 		dasd_profile_init(&block->profile, block->debugfs_dentry);
254 		if (dasd_global_profile_level == DASD_PROFILE_ON)
255 			dasd_profile_on(&device->block->profile);
256 	}
257 	device->debugfs_dentry =
258 		debugfs_create_dir(dev_name(&device->cdev->dev),
259 				   dasd_debugfs_root_entry);
260 	dasd_profile_init(&device->profile, device->debugfs_dentry);
261 	dasd_hosts_init(device->debugfs_dentry, device);
262 
263 	/* register 'device' debug area, used for all DBF_DEV_XXX calls */
264 	device->debug_area = debug_register(dev_name(&device->cdev->dev), 4, 1,
265 					    8 * sizeof(long));
266 	debug_register_view(device->debug_area, &debug_sprintf_view);
267 	debug_set_level(device->debug_area, DBF_WARNING);
268 	DBF_DEV_EVENT(DBF_EMERG, device, "%s", "debug area created");
269 
270 	device->state = DASD_STATE_BASIC;
271 
272 	return rc;
273 }
274 
275 /*
276  * Release the irq line for the device. Terminate any running i/o.
277  */
278 static int dasd_state_basic_to_known(struct dasd_device *device)
279 {
280 	int rc;
281 
282 	if (device->discipline->basic_to_known) {
283 		rc = device->discipline->basic_to_known(device);
284 		if (rc)
285 			return rc;
286 	}
287 
288 	if (device->block) {
289 		dasd_profile_exit(&device->block->profile);
290 		debugfs_remove(device->block->debugfs_dentry);
291 		dasd_gendisk_free(device->block);
292 		dasd_block_clear_timer(device->block);
293 	}
294 	rc = dasd_flush_device_queue(device);
295 	if (rc)
296 		return rc;
297 	dasd_device_clear_timer(device);
298 	dasd_profile_exit(&device->profile);
299 	dasd_hosts_exit(device);
300 	debugfs_remove(device->debugfs_dentry);
301 	DBF_DEV_EVENT(DBF_EMERG, device, "%p debug area deleted", device);
302 	if (device->debug_area != NULL) {
303 		debug_unregister(device->debug_area);
304 		device->debug_area = NULL;
305 	}
306 	device->state = DASD_STATE_KNOWN;
307 	return 0;
308 }
309 
310 /*
311  * Do the initial analysis. The do_analysis function may return
312  * -EAGAIN in which case the device keeps the state DASD_STATE_BASIC
313  * until the discipline decides to continue the startup sequence
314  * by calling the function dasd_change_state. The eckd disciplines
315  * uses this to start a ccw that detects the format. The completion
316  * interrupt for this detection ccw uses the kernel event daemon to
317  * trigger the call to dasd_change_state. All this is done in the
318  * discipline code, see dasd_eckd.c.
319  * After the analysis ccw is done (do_analysis returned 0) the block
320  * device is setup.
321  * In case the analysis returns an error, the device setup is stopped
322  * (a fake disk was already added to allow formatting).
323  */
324 static int dasd_state_basic_to_ready(struct dasd_device *device)
325 {
326 	struct dasd_block *block = device->block;
327 	struct queue_limits lim;
328 	int rc = 0;
329 
330 	/* make disk known with correct capacity */
331 	if (!block) {
332 		device->state = DASD_STATE_READY;
333 		goto out;
334 	}
335 
336 	if (block->base->discipline->do_analysis != NULL)
337 		rc = block->base->discipline->do_analysis(block);
338 	if (rc) {
339 		if (rc == -EAGAIN)
340 			return rc;
341 		device->state = DASD_STATE_UNFMT;
342 		kobject_uevent(&disk_to_dev(device->block->gdp)->kobj,
343 			       KOBJ_CHANGE);
344 		goto out;
345 	}
346 
347 	lim = queue_limits_start_update(block->gdp->queue);
348 	lim.max_dev_sectors = device->discipline->max_sectors(block);
349 	lim.max_hw_sectors = lim.max_dev_sectors;
350 	lim.logical_block_size = block->bp_block;
351 	/*
352 	 * Adjust dma_alignment to match block_size - 1
353 	 * to ensure proper buffer alignment checks in the block layer.
354 	 */
355 	lim.dma_alignment = lim.logical_block_size - 1;
356 
357 	if (device->features & DASD_FEATURE_DISCARD) {
358 		unsigned int max_bytes;
359 
360 		if (device->discipline->disc_limits) {
361 			device->discipline->disc_limits(block, &lim);
362 		} else {
363 			lim.discard_granularity = block->bp_block;
364 			/* Calculate max_discard_sectors and make it PAGE aligned */
365 			max_bytes = USHRT_MAX * block->bp_block;
366 			max_bytes = ALIGN_DOWN(max_bytes, PAGE_SIZE);
367 			lim.max_hw_discard_sectors = max_bytes / block->bp_block;
368 			lim.max_write_zeroes_sectors = lim.max_hw_discard_sectors;
369 		}
370 	}
371 	rc = queue_limits_commit_update(block->gdp->queue, &lim);
372 	if (rc)
373 		return rc;
374 
375 	set_capacity(block->gdp, block->blocks << block->s2b_shift);
376 	device->state = DASD_STATE_READY;
377 
378 	rc = dasd_scan_partitions(block);
379 	if (rc) {
380 		device->state = DASD_STATE_BASIC;
381 		return rc;
382 	}
383 
384 out:
385 	if (device->discipline->basic_to_ready)
386 		rc = device->discipline->basic_to_ready(device);
387 	return rc;
388 }
389 
390 static inline
391 int _wait_for_empty_queues(struct dasd_device *device)
392 {
393 	if (device->block)
394 		return list_empty(&device->ccw_queue) &&
395 			list_empty(&device->block->ccw_queue) &&
396 			list_empty(&device->block->ese_staging);
397 	else
398 		return list_empty(&device->ccw_queue);
399 }
400 
401 /*
402  * Remove device from block device layer. Destroy dirty buffers.
403  * Forget format information. Check if the target level is basic
404  * and if it is create fake disk for formatting.
405  */
406 static int dasd_state_ready_to_basic(struct dasd_device *device)
407 {
408 	int rc;
409 
410 	device->state = DASD_STATE_BASIC;
411 	if (device->block) {
412 		struct dasd_block *block = device->block;
413 		rc = dasd_flush_block_queue(block);
414 		if (rc) {
415 			device->state = DASD_STATE_READY;
416 			return rc;
417 		}
418 		dasd_destroy_partitions(block);
419 		block->blocks = 0;
420 		block->bp_block = 0;
421 		block->s2b_shift = 0;
422 	}
423 	return 0;
424 }
425 
426 /*
427  * Back to basic.
428  */
429 static int dasd_state_unfmt_to_basic(struct dasd_device *device)
430 {
431 	device->state = DASD_STATE_BASIC;
432 	return 0;
433 }
434 
435 /*
436  * Make the device online and schedule the bottom half to start
437  * the requeueing of requests from the linux request queue to the
438  * ccw queue.
439  */
440 static int
441 dasd_state_ready_to_online(struct dasd_device * device)
442 {
443 	device->state = DASD_STATE_ONLINE;
444 	if (device->block) {
445 		dasd_schedule_block_bh(device->block);
446 		if ((device->features & DASD_FEATURE_USERAW)) {
447 			kobject_uevent(&disk_to_dev(device->block->gdp)->kobj,
448 					KOBJ_CHANGE);
449 			return 0;
450 		}
451 		disk_uevent(file_bdev(device->block->bdev_file)->bd_disk,
452 			    KOBJ_CHANGE);
453 	}
454 	return 0;
455 }
456 
457 /*
458  * Stop the requeueing of requests again.
459  */
460 static int dasd_state_online_to_ready(struct dasd_device *device)
461 {
462 	int rc;
463 
464 	if (device->discipline->online_to_ready) {
465 		rc = device->discipline->online_to_ready(device);
466 		if (rc)
467 			return rc;
468 	}
469 
470 	device->state = DASD_STATE_READY;
471 	if (device->block && !(device->features & DASD_FEATURE_USERAW))
472 		disk_uevent(file_bdev(device->block->bdev_file)->bd_disk,
473 			    KOBJ_CHANGE);
474 	return 0;
475 }
476 
477 /*
478  * Device startup state changes.
479  */
480 static int dasd_increase_state(struct dasd_device *device)
481 {
482 	int rc;
483 
484 	rc = 0;
485 	if (device->state == DASD_STATE_NEW &&
486 	    device->target >= DASD_STATE_KNOWN)
487 		rc = dasd_state_new_to_known(device);
488 
489 	if (!rc &&
490 	    device->state == DASD_STATE_KNOWN &&
491 	    device->target >= DASD_STATE_BASIC)
492 		rc = dasd_state_known_to_basic(device);
493 
494 	if (!rc &&
495 	    device->state == DASD_STATE_BASIC &&
496 	    device->target >= DASD_STATE_READY)
497 		rc = dasd_state_basic_to_ready(device);
498 
499 	if (!rc &&
500 	    device->state == DASD_STATE_UNFMT &&
501 	    device->target > DASD_STATE_UNFMT)
502 		rc = -EPERM;
503 
504 	if (!rc &&
505 	    device->state == DASD_STATE_READY &&
506 	    device->target >= DASD_STATE_ONLINE)
507 		rc = dasd_state_ready_to_online(device);
508 
509 	return rc;
510 }
511 
512 /*
513  * Device shutdown state changes.
514  */
515 static int dasd_decrease_state(struct dasd_device *device)
516 {
517 	int rc;
518 
519 	rc = 0;
520 	if (device->state == DASD_STATE_ONLINE &&
521 	    device->target <= DASD_STATE_READY)
522 		rc = dasd_state_online_to_ready(device);
523 
524 	if (!rc &&
525 	    device->state == DASD_STATE_READY &&
526 	    device->target <= DASD_STATE_BASIC)
527 		rc = dasd_state_ready_to_basic(device);
528 
529 	if (!rc &&
530 	    device->state == DASD_STATE_UNFMT &&
531 	    device->target <= DASD_STATE_BASIC)
532 		rc = dasd_state_unfmt_to_basic(device);
533 
534 	if (!rc &&
535 	    device->state == DASD_STATE_BASIC &&
536 	    device->target <= DASD_STATE_KNOWN)
537 		rc = dasd_state_basic_to_known(device);
538 
539 	if (!rc &&
540 	    device->state == DASD_STATE_KNOWN &&
541 	    device->target <= DASD_STATE_NEW)
542 		rc = dasd_state_known_to_new(device);
543 
544 	return rc;
545 }
546 
547 /*
548  * This is the main startup/shutdown routine.
549  */
550 static void dasd_change_state(struct dasd_device *device)
551 {
552 	int rc;
553 
554 	if (device->state == device->target)
555 		/* Already where we want to go today... */
556 		return;
557 	if (device->state < device->target)
558 		rc = dasd_increase_state(device);
559 	else
560 		rc = dasd_decrease_state(device);
561 	if (rc == -EAGAIN)
562 		return;
563 	if (rc)
564 		device->target = device->state;
565 
566 	/* let user-space know that the device status changed */
567 	kobject_uevent(&device->cdev->dev.kobj, KOBJ_CHANGE);
568 
569 	if (device->state == device->target)
570 		wake_up(&dasd_init_waitq);
571 }
572 
573 /*
574  * Kick starter for devices that did not complete the startup/shutdown
575  * procedure or were sleeping because of a pending state.
576  * dasd_kick_device will schedule a call do do_kick_device to the kernel
577  * event daemon.
578  */
579 static void do_kick_device(struct work_struct *work)
580 {
581 	struct dasd_device *device = container_of(work, struct dasd_device, kick_work);
582 	mutex_lock(&device->state_mutex);
583 	dasd_change_state(device);
584 	mutex_unlock(&device->state_mutex);
585 	dasd_schedule_device_bh(device);
586 	dasd_put_device(device);
587 }
588 
589 void dasd_kick_device(struct dasd_device *device)
590 {
591 	dasd_get_device(device);
592 	/* queue call to dasd_kick_device to the kernel event daemon. */
593 	if (!schedule_work(&device->kick_work))
594 		dasd_put_device(device);
595 }
596 EXPORT_SYMBOL(dasd_kick_device);
597 
598 /*
599  * dasd_reload_device will schedule a call do do_reload_device to the kernel
600  * event daemon.
601  */
602 static void do_reload_device(struct work_struct *work)
603 {
604 	struct dasd_device *device = container_of(work, struct dasd_device,
605 						  reload_device);
606 	device->discipline->reload(device);
607 	dasd_put_device(device);
608 }
609 
610 void dasd_reload_device(struct dasd_device *device)
611 {
612 	dasd_get_device(device);
613 	/* queue call to dasd_reload_device to the kernel event daemon. */
614 	if (!schedule_work(&device->reload_device))
615 		dasd_put_device(device);
616 }
617 EXPORT_SYMBOL(dasd_reload_device);
618 
619 /*
620  * Set the target state for a device and starts the state change.
621  */
622 void dasd_set_target_state(struct dasd_device *device, int target)
623 {
624 	dasd_get_device(device);
625 	mutex_lock(&device->state_mutex);
626 	/* If we are in probeonly mode stop at DASD_STATE_READY. */
627 	if (dasd_probeonly && target > DASD_STATE_READY)
628 		target = DASD_STATE_READY;
629 	if (device->target != target) {
630 		if (device->state == target)
631 			wake_up(&dasd_init_waitq);
632 		device->target = target;
633 	}
634 	if (device->state != device->target)
635 		dasd_change_state(device);
636 	mutex_unlock(&device->state_mutex);
637 	dasd_put_device(device);
638 }
639 
640 /*
641  * Enable devices with device numbers in [from..to].
642  */
643 static inline int _wait_for_device(struct dasd_device *device)
644 {
645 	return (device->state == device->target);
646 }
647 
648 void dasd_enable_device(struct dasd_device *device)
649 {
650 	dasd_set_target_state(device, DASD_STATE_ONLINE);
651 	if (device->state <= DASD_STATE_KNOWN)
652 		/* No discipline for device found. */
653 		dasd_set_target_state(device, DASD_STATE_NEW);
654 	/* Now wait for the devices to come up. */
655 	wait_event(dasd_init_waitq, _wait_for_device(device));
656 
657 	dasd_reload_device(device);
658 	if (device->discipline->kick_validate)
659 		device->discipline->kick_validate(device);
660 }
661 EXPORT_SYMBOL(dasd_enable_device);
662 
663 /*
664  * SECTION: device operation (interrupt handler, start i/o, term i/o ...)
665  */
666 
667 unsigned int dasd_global_profile_level = DASD_PROFILE_OFF;
668 
669 #ifdef CONFIG_DASD_PROFILE
670 struct dasd_profile dasd_global_profile = {
671 	.lock = __SPIN_LOCK_UNLOCKED(dasd_global_profile.lock),
672 };
673 static struct dentry *dasd_debugfs_global_entry;
674 
675 /*
676  * Add profiling information for cqr before execution.
677  */
678 static void dasd_profile_start(struct dasd_block *block,
679 			       struct dasd_ccw_req *cqr,
680 			       struct request *req)
681 {
682 	struct list_head *l;
683 	unsigned int counter;
684 	struct dasd_device *device;
685 
686 	/* count the length of the chanq for statistics */
687 	counter = 0;
688 	if (dasd_global_profile_level || block->profile.data)
689 		list_for_each(l, &block->ccw_queue)
690 			if (++counter >= 31)
691 				break;
692 
693 	spin_lock(&dasd_global_profile.lock);
694 	if (dasd_global_profile.data) {
695 		dasd_global_profile.data->dasd_io_nr_req[counter]++;
696 		if (rq_data_dir(req) == READ)
697 			dasd_global_profile.data->dasd_read_nr_req[counter]++;
698 	}
699 	spin_unlock(&dasd_global_profile.lock);
700 
701 	spin_lock(&block->profile.lock);
702 	if (block->profile.data) {
703 		block->profile.data->dasd_io_nr_req[counter]++;
704 		if (rq_data_dir(req) == READ)
705 			block->profile.data->dasd_read_nr_req[counter]++;
706 	}
707 	spin_unlock(&block->profile.lock);
708 
709 	/*
710 	 * We count the request for the start device, even though it may run on
711 	 * some other device due to error recovery. This way we make sure that
712 	 * we count each request only once.
713 	 */
714 	device = cqr->startdev;
715 	if (!device->profile.data)
716 		return;
717 
718 	spin_lock(get_ccwdev_lock(device->cdev));
719 	counter = 1; /* request is not yet queued on the start device */
720 	list_for_each(l, &device->ccw_queue)
721 		if (++counter >= 31)
722 			break;
723 	spin_unlock(get_ccwdev_lock(device->cdev));
724 
725 	spin_lock(&device->profile.lock);
726 	device->profile.data->dasd_io_nr_req[counter]++;
727 	if (rq_data_dir(req) == READ)
728 		device->profile.data->dasd_read_nr_req[counter]++;
729 	spin_unlock(&device->profile.lock);
730 }
731 
732 /*
733  * Add profiling information for cqr after execution.
734  */
735 
736 #define dasd_profile_counter(value, index)			   \
737 {								   \
738 	for (index = 0; index < 31 && value >> (2+index); index++) \
739 		;						   \
740 }
741 
742 static void dasd_profile_end_add_data(struct dasd_profile_info *data,
743 				      int is_alias,
744 				      int is_tpm,
745 				      int is_read,
746 				      long sectors,
747 				      int sectors_ind,
748 				      int tottime_ind,
749 				      int tottimeps_ind,
750 				      int strtime_ind,
751 				      int irqtime_ind,
752 				      int irqtimeps_ind,
753 				      int endtime_ind)
754 {
755 	/* in case of an overflow, reset the whole profile */
756 	if (data->dasd_io_reqs == UINT_MAX) {
757 			memset(data, 0, sizeof(*data));
758 			ktime_get_real_ts64(&data->starttod);
759 	}
760 	data->dasd_io_reqs++;
761 	data->dasd_io_sects += sectors;
762 	if (is_alias)
763 		data->dasd_io_alias++;
764 	if (is_tpm)
765 		data->dasd_io_tpm++;
766 
767 	data->dasd_io_secs[sectors_ind]++;
768 	data->dasd_io_times[tottime_ind]++;
769 	data->dasd_io_timps[tottimeps_ind]++;
770 	data->dasd_io_time1[strtime_ind]++;
771 	data->dasd_io_time2[irqtime_ind]++;
772 	data->dasd_io_time2ps[irqtimeps_ind]++;
773 	data->dasd_io_time3[endtime_ind]++;
774 
775 	if (is_read) {
776 		data->dasd_read_reqs++;
777 		data->dasd_read_sects += sectors;
778 		if (is_alias)
779 			data->dasd_read_alias++;
780 		if (is_tpm)
781 			data->dasd_read_tpm++;
782 		data->dasd_read_secs[sectors_ind]++;
783 		data->dasd_read_times[tottime_ind]++;
784 		data->dasd_read_time1[strtime_ind]++;
785 		data->dasd_read_time2[irqtime_ind]++;
786 		data->dasd_read_time3[endtime_ind]++;
787 	}
788 }
789 
790 static void dasd_profile_end(struct dasd_block *block,
791 			     struct dasd_ccw_req *cqr,
792 			     struct request *req)
793 {
794 	unsigned long strtime, irqtime, endtime, tottime;
795 	unsigned long tottimeps, sectors;
796 	struct dasd_device *device;
797 	int sectors_ind, tottime_ind, tottimeps_ind, strtime_ind;
798 	int irqtime_ind, irqtimeps_ind, endtime_ind;
799 	struct dasd_profile_info *data;
800 
801 	device = cqr->startdev;
802 	if (!(dasd_global_profile_level ||
803 	      block->profile.data ||
804 	      device->profile.data))
805 		return;
806 
807 	sectors = blk_rq_sectors(req);
808 	if (!cqr->buildclk || !cqr->startclk ||
809 	    !cqr->stopclk || !cqr->endclk ||
810 	    !sectors)
811 		return;
812 
813 	strtime = ((cqr->startclk - cqr->buildclk) >> 12);
814 	irqtime = ((cqr->stopclk - cqr->startclk) >> 12);
815 	endtime = ((cqr->endclk - cqr->stopclk) >> 12);
816 	tottime = ((cqr->endclk - cqr->buildclk) >> 12);
817 	tottimeps = tottime / sectors;
818 
819 	dasd_profile_counter(sectors, sectors_ind);
820 	dasd_profile_counter(tottime, tottime_ind);
821 	dasd_profile_counter(tottimeps, tottimeps_ind);
822 	dasd_profile_counter(strtime, strtime_ind);
823 	dasd_profile_counter(irqtime, irqtime_ind);
824 	dasd_profile_counter(irqtime / sectors, irqtimeps_ind);
825 	dasd_profile_counter(endtime, endtime_ind);
826 
827 	spin_lock(&dasd_global_profile.lock);
828 	if (dasd_global_profile.data) {
829 		data = dasd_global_profile.data;
830 		data->dasd_sum_times += tottime;
831 		data->dasd_sum_time_str += strtime;
832 		data->dasd_sum_time_irq += irqtime;
833 		data->dasd_sum_time_end += endtime;
834 		dasd_profile_end_add_data(dasd_global_profile.data,
835 					  cqr->startdev != block->base,
836 					  cqr->cpmode == 1,
837 					  rq_data_dir(req) == READ,
838 					  sectors, sectors_ind, tottime_ind,
839 					  tottimeps_ind, strtime_ind,
840 					  irqtime_ind, irqtimeps_ind,
841 					  endtime_ind);
842 	}
843 	spin_unlock(&dasd_global_profile.lock);
844 
845 	spin_lock(&block->profile.lock);
846 	if (block->profile.data) {
847 		data = block->profile.data;
848 		data->dasd_sum_times += tottime;
849 		data->dasd_sum_time_str += strtime;
850 		data->dasd_sum_time_irq += irqtime;
851 		data->dasd_sum_time_end += endtime;
852 		dasd_profile_end_add_data(block->profile.data,
853 					  cqr->startdev != block->base,
854 					  cqr->cpmode == 1,
855 					  rq_data_dir(req) == READ,
856 					  sectors, sectors_ind, tottime_ind,
857 					  tottimeps_ind, strtime_ind,
858 					  irqtime_ind, irqtimeps_ind,
859 					  endtime_ind);
860 	}
861 	spin_unlock(&block->profile.lock);
862 
863 	spin_lock(&device->profile.lock);
864 	if (device->profile.data) {
865 		data = device->profile.data;
866 		data->dasd_sum_times += tottime;
867 		data->dasd_sum_time_str += strtime;
868 		data->dasd_sum_time_irq += irqtime;
869 		data->dasd_sum_time_end += endtime;
870 		dasd_profile_end_add_data(device->profile.data,
871 					  cqr->startdev != block->base,
872 					  cqr->cpmode == 1,
873 					  rq_data_dir(req) == READ,
874 					  sectors, sectors_ind, tottime_ind,
875 					  tottimeps_ind, strtime_ind,
876 					  irqtime_ind, irqtimeps_ind,
877 					  endtime_ind);
878 	}
879 	spin_unlock(&device->profile.lock);
880 }
881 
882 void dasd_profile_reset(struct dasd_profile *profile)
883 {
884 	struct dasd_profile_info *data;
885 
886 	spin_lock_bh(&profile->lock);
887 	data = profile->data;
888 	if (!data) {
889 		spin_unlock_bh(&profile->lock);
890 		return;
891 	}
892 	memset(data, 0, sizeof(*data));
893 	ktime_get_real_ts64(&data->starttod);
894 	spin_unlock_bh(&profile->lock);
895 }
896 
897 int dasd_profile_on(struct dasd_profile *profile)
898 {
899 	struct dasd_profile_info *data;
900 
901 	data = kzalloc_obj(*data);
902 	if (!data)
903 		return -ENOMEM;
904 	spin_lock_bh(&profile->lock);
905 	if (profile->data) {
906 		spin_unlock_bh(&profile->lock);
907 		kfree(data);
908 		return 0;
909 	}
910 	ktime_get_real_ts64(&data->starttod);
911 	profile->data = data;
912 	spin_unlock_bh(&profile->lock);
913 	return 0;
914 }
915 
916 void dasd_profile_off(struct dasd_profile *profile)
917 {
918 	spin_lock_bh(&profile->lock);
919 	kfree(profile->data);
920 	profile->data = NULL;
921 	spin_unlock_bh(&profile->lock);
922 }
923 
924 char *dasd_get_user_string(const char __user *user_buf, size_t user_len)
925 {
926 	char *buffer;
927 
928 	buffer = vmalloc(user_len + 1);
929 	if (buffer == NULL)
930 		return ERR_PTR(-ENOMEM);
931 	if (copy_from_user(buffer, user_buf, user_len) != 0) {
932 		vfree(buffer);
933 		return ERR_PTR(-EFAULT);
934 	}
935 	/* got the string, now strip linefeed. */
936 	if (buffer[user_len - 1] == '\n')
937 		buffer[user_len - 1] = 0;
938 	else
939 		buffer[user_len] = 0;
940 	return buffer;
941 }
942 
943 static ssize_t dasd_stats_write(struct file *file,
944 				const char __user *user_buf,
945 				size_t user_len, loff_t *pos)
946 {
947 	char *buffer, *str;
948 	int rc;
949 	struct seq_file *m = (struct seq_file *)file->private_data;
950 	struct dasd_profile *prof = m->private;
951 
952 	if (user_len > 65536)
953 		user_len = 65536;
954 	buffer = dasd_get_user_string(user_buf, user_len);
955 	if (IS_ERR(buffer))
956 		return PTR_ERR(buffer);
957 
958 	str = skip_spaces(buffer);
959 	rc = user_len;
960 	if (strncmp(str, "reset", 5) == 0) {
961 		dasd_profile_reset(prof);
962 	} else if (strncmp(str, "on", 2) == 0) {
963 		rc = dasd_profile_on(prof);
964 		if (rc)
965 			goto out;
966 		rc = user_len;
967 		if (prof == &dasd_global_profile) {
968 			dasd_profile_reset(prof);
969 			dasd_global_profile_level = DASD_PROFILE_GLOBAL_ONLY;
970 		}
971 	} else if (strncmp(str, "off", 3) == 0) {
972 		if (prof == &dasd_global_profile)
973 			dasd_global_profile_level = DASD_PROFILE_OFF;
974 		dasd_profile_off(prof);
975 	} else
976 		rc = -EINVAL;
977 out:
978 	vfree(buffer);
979 	return rc;
980 }
981 
982 static void dasd_stats_array(struct seq_file *m, unsigned int *array)
983 {
984 	int i;
985 
986 	for (i = 0; i < 32; i++)
987 		seq_printf(m, "%u ", array[i]);
988 	seq_putc(m, '\n');
989 }
990 
991 static void dasd_stats_seq_print(struct seq_file *m,
992 				 struct dasd_profile_info *data)
993 {
994 	seq_printf(m, "start_time %ptSp\n", &data->starttod);
995 	seq_printf(m, "total_requests %u\n", data->dasd_io_reqs);
996 	seq_printf(m, "total_sectors %u\n", data->dasd_io_sects);
997 	seq_printf(m, "total_pav %u\n", data->dasd_io_alias);
998 	seq_printf(m, "total_hpf %u\n", data->dasd_io_tpm);
999 	seq_printf(m, "avg_total %lu\n", data->dasd_io_reqs ?
1000 		   data->dasd_sum_times / data->dasd_io_reqs : 0UL);
1001 	seq_printf(m, "avg_build_to_ssch %lu\n", data->dasd_io_reqs ?
1002 		   data->dasd_sum_time_str / data->dasd_io_reqs : 0UL);
1003 	seq_printf(m, "avg_ssch_to_irq %lu\n", data->dasd_io_reqs ?
1004 		   data->dasd_sum_time_irq / data->dasd_io_reqs : 0UL);
1005 	seq_printf(m, "avg_irq_to_end %lu\n", data->dasd_io_reqs ?
1006 		   data->dasd_sum_time_end / data->dasd_io_reqs : 0UL);
1007 	seq_puts(m, "histogram_sectors ");
1008 	dasd_stats_array(m, data->dasd_io_secs);
1009 	seq_puts(m, "histogram_io_times ");
1010 	dasd_stats_array(m, data->dasd_io_times);
1011 	seq_puts(m, "histogram_io_times_weighted ");
1012 	dasd_stats_array(m, data->dasd_io_timps);
1013 	seq_puts(m, "histogram_time_build_to_ssch ");
1014 	dasd_stats_array(m, data->dasd_io_time1);
1015 	seq_puts(m, "histogram_time_ssch_to_irq ");
1016 	dasd_stats_array(m, data->dasd_io_time2);
1017 	seq_puts(m, "histogram_time_ssch_to_irq_weighted ");
1018 	dasd_stats_array(m, data->dasd_io_time2ps);
1019 	seq_puts(m, "histogram_time_irq_to_end ");
1020 	dasd_stats_array(m, data->dasd_io_time3);
1021 	seq_puts(m, "histogram_ccw_queue_length ");
1022 	dasd_stats_array(m, data->dasd_io_nr_req);
1023 	seq_printf(m, "total_read_requests %u\n", data->dasd_read_reqs);
1024 	seq_printf(m, "total_read_sectors %u\n", data->dasd_read_sects);
1025 	seq_printf(m, "total_read_pav %u\n", data->dasd_read_alias);
1026 	seq_printf(m, "total_read_hpf %u\n", data->dasd_read_tpm);
1027 	seq_puts(m, "histogram_read_sectors ");
1028 	dasd_stats_array(m, data->dasd_read_secs);
1029 	seq_puts(m, "histogram_read_times ");
1030 	dasd_stats_array(m, data->dasd_read_times);
1031 	seq_puts(m, "histogram_read_time_build_to_ssch ");
1032 	dasd_stats_array(m, data->dasd_read_time1);
1033 	seq_puts(m, "histogram_read_time_ssch_to_irq ");
1034 	dasd_stats_array(m, data->dasd_read_time2);
1035 	seq_puts(m, "histogram_read_time_irq_to_end ");
1036 	dasd_stats_array(m, data->dasd_read_time3);
1037 	seq_puts(m, "histogram_read_ccw_queue_length ");
1038 	dasd_stats_array(m, data->dasd_read_nr_req);
1039 }
1040 
1041 static int dasd_stats_show(struct seq_file *m, void *v)
1042 {
1043 	struct dasd_profile *profile;
1044 	struct dasd_profile_info *data;
1045 
1046 	profile = m->private;
1047 	spin_lock_bh(&profile->lock);
1048 	data = profile->data;
1049 	if (!data) {
1050 		spin_unlock_bh(&profile->lock);
1051 		seq_puts(m, "disabled\n");
1052 		return 0;
1053 	}
1054 	dasd_stats_seq_print(m, data);
1055 	spin_unlock_bh(&profile->lock);
1056 	return 0;
1057 }
1058 
1059 static int dasd_stats_open(struct inode *inode, struct file *file)
1060 {
1061 	struct dasd_profile *profile = inode->i_private;
1062 	return single_open(file, dasd_stats_show, profile);
1063 }
1064 
1065 static const struct file_operations dasd_stats_raw_fops = {
1066 	.owner		= THIS_MODULE,
1067 	.open		= dasd_stats_open,
1068 	.read		= seq_read,
1069 	.llseek		= seq_lseek,
1070 	.release	= single_release,
1071 	.write		= dasd_stats_write,
1072 };
1073 
1074 static void dasd_profile_init(struct dasd_profile *profile,
1075 			      struct dentry *base_dentry)
1076 {
1077 	profile->data = NULL;
1078 	profile->dentry = debugfs_create_file("statistics", 0600, base_dentry,
1079 					      profile, &dasd_stats_raw_fops);
1080 }
1081 
1082 static void dasd_profile_exit(struct dasd_profile *profile)
1083 {
1084 	dasd_profile_off(profile);
1085 	debugfs_remove(profile->dentry);
1086 	profile->dentry = NULL;
1087 }
1088 
1089 static void dasd_statistics_removeroot(void)
1090 {
1091 	dasd_global_profile_level = DASD_PROFILE_OFF;
1092 	dasd_profile_exit(&dasd_global_profile);
1093 	debugfs_remove(dasd_debugfs_global_entry);
1094 	debugfs_remove(dasd_debugfs_root_entry);
1095 }
1096 
1097 static void dasd_statistics_createroot(void)
1098 {
1099 	dasd_debugfs_root_entry = debugfs_create_dir("dasd", NULL);
1100 	dasd_debugfs_global_entry = debugfs_create_dir("global", dasd_debugfs_root_entry);
1101 	dasd_profile_init(&dasd_global_profile, dasd_debugfs_global_entry);
1102 }
1103 
1104 #else
1105 #define dasd_profile_start(block, cqr, req) do {} while (0)
1106 #define dasd_profile_end(block, cqr, req) do {} while (0)
1107 
1108 static void dasd_statistics_createroot(void)
1109 {
1110 	return;
1111 }
1112 
1113 static void dasd_statistics_removeroot(void)
1114 {
1115 	return;
1116 }
1117 
1118 static void dasd_profile_init(struct dasd_profile *profile,
1119 			      struct dentry *base_dentry)
1120 {
1121 	return;
1122 }
1123 
1124 static void dasd_profile_exit(struct dasd_profile *profile)
1125 {
1126 	return;
1127 }
1128 
1129 int dasd_profile_on(struct dasd_profile *profile)
1130 {
1131 	return 0;
1132 }
1133 
1134 #endif				/* CONFIG_DASD_PROFILE */
1135 
1136 static int dasd_hosts_show(struct seq_file *m, void *v)
1137 {
1138 	struct dasd_device *device;
1139 	int rc = -EOPNOTSUPP;
1140 
1141 	device = m->private;
1142 	dasd_get_device(device);
1143 
1144 	if (device->discipline->hosts_print)
1145 		rc = device->discipline->hosts_print(device, m);
1146 
1147 	dasd_put_device(device);
1148 	return rc;
1149 }
1150 
1151 DEFINE_SHOW_ATTRIBUTE(dasd_hosts);
1152 
1153 static void dasd_hosts_exit(struct dasd_device *device)
1154 {
1155 	debugfs_remove(device->hosts_dentry);
1156 	device->hosts_dentry = NULL;
1157 }
1158 
1159 static void dasd_hosts_init(struct dentry *base_dentry,
1160 			    struct dasd_device *device)
1161 {
1162 	device->hosts_dentry = debugfs_create_file("host_access_list", 0400, base_dentry,
1163 						   device, &dasd_hosts_fops);
1164 }
1165 
1166 struct dasd_ccw_req *dasd_smalloc_request(int magic, int cplength, int datasize,
1167 					  struct dasd_device *device,
1168 					  struct dasd_ccw_req *cqr)
1169 {
1170 	unsigned long flags;
1171 	char *data, *chunk;
1172 	int size = 0;
1173 
1174 	if (cplength > 0)
1175 		size += cplength * sizeof(struct ccw1);
1176 	if (datasize > 0)
1177 		size += datasize;
1178 	if (!cqr)
1179 		size += (sizeof(*cqr) + 7L) & -8L;
1180 
1181 	spin_lock_irqsave(&device->mem_lock, flags);
1182 	data = chunk = dasd_alloc_chunk(&device->ccw_chunks, size);
1183 	spin_unlock_irqrestore(&device->mem_lock, flags);
1184 	if (!chunk)
1185 		return ERR_PTR(-ENOMEM);
1186 	if (!cqr) {
1187 		cqr = (void *) data;
1188 		data += (sizeof(*cqr) + 7L) & -8L;
1189 	}
1190 	memset(cqr, 0, sizeof(*cqr));
1191 	cqr->mem_chunk = chunk;
1192 	if (cplength > 0) {
1193 		cqr->cpaddr = data;
1194 		data += cplength * sizeof(struct ccw1);
1195 		memset(cqr->cpaddr, 0, cplength * sizeof(struct ccw1));
1196 	}
1197 	if (datasize > 0) {
1198 		cqr->data = data;
1199  		memset(cqr->data, 0, datasize);
1200 	}
1201 	cqr->magic = magic;
1202 	set_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags);
1203 	dasd_get_device(device);
1204 	return cqr;
1205 }
1206 EXPORT_SYMBOL(dasd_smalloc_request);
1207 
1208 struct dasd_ccw_req *dasd_fmalloc_request(int magic, int cplength,
1209 					  int datasize,
1210 					  struct dasd_device *device)
1211 {
1212 	struct dasd_ccw_req *cqr;
1213 	unsigned long flags;
1214 	int size, cqr_size;
1215 	char *data;
1216 
1217 	cqr_size = (sizeof(*cqr) + 7L) & -8L;
1218 	size = cqr_size;
1219 	if (cplength > 0)
1220 		size += cplength * sizeof(struct ccw1);
1221 	if (datasize > 0)
1222 		size += datasize;
1223 
1224 	spin_lock_irqsave(&device->mem_lock, flags);
1225 	cqr = dasd_alloc_chunk(&device->ese_chunks, size);
1226 	spin_unlock_irqrestore(&device->mem_lock, flags);
1227 	if (!cqr)
1228 		return ERR_PTR(-ENOMEM);
1229 	memset(cqr, 0, sizeof(*cqr));
1230 	data = (char *)cqr + cqr_size;
1231 	cqr->cpaddr = NULL;
1232 	if (cplength > 0) {
1233 		cqr->cpaddr = data;
1234 		data += cplength * sizeof(struct ccw1);
1235 		memset(cqr->cpaddr, 0, cplength * sizeof(struct ccw1));
1236 	}
1237 	cqr->data = NULL;
1238 	if (datasize > 0) {
1239 		cqr->data = data;
1240 		memset(cqr->data, 0, datasize);
1241 	}
1242 
1243 	cqr->magic = magic;
1244 	set_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags);
1245 	dasd_get_device(device);
1246 
1247 	return cqr;
1248 }
1249 EXPORT_SYMBOL(dasd_fmalloc_request);
1250 
1251 void dasd_sfree_request(struct dasd_ccw_req *cqr, struct dasd_device *device)
1252 {
1253 	unsigned long flags;
1254 
1255 	spin_lock_irqsave(&device->mem_lock, flags);
1256 	/*
1257 	 * Free the request block from the pool it came from: smalloc() sets
1258 	 * mem_chunk (ccw_chunks), fmalloc() leaves it NULL (ese_chunks). A
1259 	 * full-track request also frees its track-filler buffer.
1260 	 */
1261 	if (cqr->filldata)
1262 		dasd_free_chunk(&device->fill_chunks, cqr->filldata);
1263 	if (cqr->mem_chunk)
1264 		dasd_free_chunk(&device->ccw_chunks, cqr->mem_chunk);
1265 	else
1266 		dasd_free_chunk(&device->ese_chunks, cqr);
1267 
1268 	spin_unlock_irqrestore(&device->mem_lock, flags);
1269 	dasd_put_device(device);
1270 }
1271 EXPORT_SYMBOL(dasd_sfree_request);
1272 
1273 void dasd_ffree_request(struct dasd_ccw_req *cqr, struct dasd_device *device)
1274 {
1275 	unsigned long flags;
1276 
1277 	spin_lock_irqsave(&device->mem_lock, flags);
1278 	if (cqr->filldata)
1279 		dasd_free_chunk(&device->fill_chunks, cqr->filldata);
1280 	dasd_free_chunk(&device->ese_chunks, cqr);
1281 	spin_unlock_irqrestore(&device->mem_lock, flags);
1282 	dasd_put_device(device);
1283 }
1284 EXPORT_SYMBOL(dasd_ffree_request);
1285 
1286 /*
1287  * Check discipline magic in cqr.
1288  */
1289 static inline int dasd_check_cqr(struct dasd_ccw_req *cqr)
1290 {
1291 	struct dasd_device *device;
1292 
1293 	if (cqr == NULL)
1294 		return -EINVAL;
1295 	device = cqr->startdev;
1296 	if (strncmp((char *) &cqr->magic, device->discipline->ebcname, 4)) {
1297 		DBF_DEV_EVENT(DBF_WARNING, device,
1298 			    " dasd_ccw_req 0x%08x magic doesn't match"
1299 			    " discipline 0x%08x",
1300 			    cqr->magic,
1301 			    *(unsigned int *) device->discipline->name);
1302 		return -EINVAL;
1303 	}
1304 	return 0;
1305 }
1306 
1307 /*
1308  * Terminate the current i/o and set the request to clear_pending.
1309  * Timer keeps device runnig.
1310  * ccw_device_clear can fail if the i/o subsystem
1311  * is in a bad mood.
1312  */
1313 int dasd_term_IO(struct dasd_ccw_req *cqr)
1314 {
1315 	struct dasd_device *device;
1316 	int retries, rc;
1317 
1318 	/* Check the cqr */
1319 	rc = dasd_check_cqr(cqr);
1320 	if (rc)
1321 		return rc;
1322 	retries = 0;
1323 	device = (struct dasd_device *) cqr->startdev;
1324 	while ((retries < 5) && (cqr->status == DASD_CQR_IN_IO)) {
1325 		rc = ccw_device_clear(device->cdev, (long) cqr);
1326 		switch (rc) {
1327 		case 0:	/* termination successful */
1328 			cqr->status = DASD_CQR_CLEAR_PENDING;
1329 			cqr->stopclk = get_tod_clock();
1330 			cqr->starttime = 0;
1331 			DBF_DEV_EVENT(DBF_DEBUG, device,
1332 				      "terminate cqr %p successful",
1333 				      cqr);
1334 			break;
1335 		case -ENODEV:
1336 			DBF_DEV_EVENT(DBF_ERR, device, "%s",
1337 				      "device gone, retry");
1338 			break;
1339 		case -EINVAL:
1340 			/*
1341 			 * device not valid so no I/O could be running
1342 			 * handle CQR as termination successful
1343 			 */
1344 			cqr->status = DASD_CQR_CLEARED;
1345 			cqr->stopclk = get_tod_clock();
1346 			cqr->starttime = 0;
1347 			/* no retries for invalid devices */
1348 			cqr->retries = -1;
1349 			DBF_DEV_EVENT(DBF_ERR, device, "%s",
1350 				      "EINVAL, handle as terminated");
1351 			/* fake rc to success */
1352 			rc = 0;
1353 			break;
1354 		default:
1355 			dev_err(&device->cdev->dev,
1356 				"Unexpected error during request termination %d\n", rc);
1357 			BUG();
1358 			break;
1359 		}
1360 		retries++;
1361 	}
1362 	dasd_schedule_device_bh(device);
1363 	return rc;
1364 }
1365 EXPORT_SYMBOL(dasd_term_IO);
1366 
1367 /*
1368  * Start the i/o. This start_IO can fail if the channel is really busy.
1369  * In that case set up a timer to start the request later.
1370  */
1371 int dasd_start_IO(struct dasd_ccw_req *cqr)
1372 {
1373 	struct dasd_device *device;
1374 	int rc;
1375 
1376 	/* Check the cqr */
1377 	rc = dasd_check_cqr(cqr);
1378 	if (rc) {
1379 		cqr->intrc = rc;
1380 		return rc;
1381 	}
1382 	device = (struct dasd_device *) cqr->startdev;
1383 	if (((cqr->block &&
1384 	      test_bit(DASD_FLAG_LOCK_STOLEN, &cqr->block->base->flags)) ||
1385 	     test_bit(DASD_FLAG_LOCK_STOLEN, &device->flags)) &&
1386 	    !test_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags)) {
1387 		DBF_DEV_EVENT(DBF_DEBUG, device, "start_IO: return request %p "
1388 			      "because of stolen lock", cqr);
1389 		cqr->status = DASD_CQR_ERROR;
1390 		cqr->intrc = -EPERM;
1391 		return -EPERM;
1392 	}
1393 	if (cqr->retries < 0) {
1394 		dev_err(&device->cdev->dev,
1395 			"Start I/O ran out of retries\n");
1396 		cqr->status = DASD_CQR_ERROR;
1397 		return -EIO;
1398 	}
1399 	dasd_start_IO_prepare(cqr);
1400 	cqr->startclk = get_tod_clock();
1401 	cqr->starttime = jiffies;
1402 	cqr->retries--;
1403 	if (!test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags)) {
1404 		cqr->lpm &= dasd_path_get_opm(device);
1405 		if (!cqr->lpm)
1406 			cqr->lpm = dasd_path_get_opm(device);
1407 	}
1408 	if (cqr->cpmode == 1) {
1409 		rc = ccw_device_tm_start(device->cdev, cqr->cpaddr,
1410 					 (long) cqr, cqr->lpm);
1411 	} else {
1412 		rc = ccw_device_start(device->cdev, cqr->cpaddr,
1413 				      (long) cqr, cqr->lpm, 0);
1414 	}
1415 	switch (rc) {
1416 	case 0:
1417 		cqr->status = DASD_CQR_IN_IO;
1418 		break;
1419 	case -EBUSY:
1420 		DBF_DEV_EVENT(DBF_WARNING, device, "%s",
1421 			      "start_IO: device busy, retry later");
1422 		break;
1423 	case -EACCES:
1424 		/* -EACCES indicates that the request used only a subset of the
1425 		 * available paths and all these paths are gone. If the lpm of
1426 		 * this request was only a subset of the opm (e.g. the ppm) then
1427 		 * we just do a retry with all available paths.
1428 		 * If we already use the full opm, something is amiss, and we
1429 		 * need a full path verification.
1430 		 */
1431 		if (test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags)) {
1432 			DBF_DEV_EVENT(DBF_WARNING, device,
1433 				      "start_IO: selected paths gone (%x)",
1434 				      cqr->lpm);
1435 		} else if (cqr->lpm != dasd_path_get_opm(device)) {
1436 			cqr->lpm = dasd_path_get_opm(device);
1437 			DBF_DEV_EVENT(DBF_DEBUG, device, "%s",
1438 				      "start_IO: selected paths gone,"
1439 				      " retry on all paths");
1440 		} else {
1441 			DBF_DEV_EVENT(DBF_WARNING, device, "%s",
1442 				      "start_IO: all paths in opm gone,"
1443 				      " do path verification");
1444 			dasd_generic_last_path_gone(device);
1445 			dasd_path_no_path(device);
1446 			dasd_path_set_tbvpm(device,
1447 					  ccw_device_get_path_mask(
1448 						  device->cdev));
1449 		}
1450 		break;
1451 	case -ENODEV:
1452 		DBF_DEV_EVENT(DBF_WARNING, device, "%s",
1453 			      "start_IO: -ENODEV device gone, retry");
1454 		/* this is equivalent to CC=3 for SSCH report this to EER */
1455 		dasd_handle_autoquiesce(device, cqr, DASD_EER_STARTIO);
1456 		break;
1457 	case -EIO:
1458 		DBF_DEV_EVENT(DBF_WARNING, device, "%s",
1459 			      "start_IO: -EIO device gone, retry");
1460 		break;
1461 	case -EINVAL:
1462 		DBF_DEV_EVENT(DBF_WARNING, device, "%s",
1463 			      "start_IO: -EINVAL device currently "
1464 			      "not accessible");
1465 		break;
1466 	default:
1467 		dev_err(&device->cdev->dev,
1468 			"Unexpected error during request start %d", rc);
1469 		BUG();
1470 		break;
1471 	}
1472 	cqr->intrc = rc;
1473 	return rc;
1474 }
1475 EXPORT_SYMBOL(dasd_start_IO);
1476 
1477 /*
1478  * Timeout function for dasd devices. This is used for different purposes
1479  *  1) missing interrupt handler for normal operation
1480  *  2) delayed start of request where start_IO failed with -EBUSY
1481  *  3) timeout for missing state change interrupts
1482  * The head of the ccw queue will have status DASD_CQR_IN_IO for 1),
1483  * DASD_CQR_QUEUED for 2) and 3).
1484  */
1485 static void dasd_device_timeout(struct timer_list *t)
1486 {
1487 	unsigned long flags;
1488 	struct dasd_device *device;
1489 
1490 	device = timer_container_of(device, t, timer);
1491 	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
1492 	/* re-activate request queue */
1493 	dasd_device_remove_stop_bits(device, DASD_STOPPED_PENDING);
1494 	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
1495 	dasd_schedule_device_bh(device);
1496 }
1497 
1498 /*
1499  * Setup timeout for a device in jiffies.
1500  */
1501 void dasd_device_set_timer(struct dasd_device *device, int expires)
1502 {
1503 	if (expires == 0)
1504 		timer_delete(&device->timer);
1505 	else
1506 		mod_timer(&device->timer, jiffies + expires);
1507 }
1508 EXPORT_SYMBOL(dasd_device_set_timer);
1509 
1510 /*
1511  * Clear timeout for a device.
1512  */
1513 void dasd_device_clear_timer(struct dasd_device *device)
1514 {
1515 	timer_delete(&device->timer);
1516 }
1517 EXPORT_SYMBOL(dasd_device_clear_timer);
1518 
1519 static void dasd_handle_killed_request(struct ccw_device *cdev,
1520 				       unsigned long intparm)
1521 {
1522 	struct dasd_ccw_req *cqr;
1523 	struct dasd_device *device;
1524 
1525 	if (!intparm)
1526 		return;
1527 	cqr = (struct dasd_ccw_req *) intparm;
1528 	if (cqr->status != DASD_CQR_IN_IO) {
1529 		DBF_EVENT_DEVID(DBF_DEBUG, cdev,
1530 				"invalid status in handle_killed_request: "
1531 				"%02x", cqr->status);
1532 		return;
1533 	}
1534 
1535 	device = dasd_device_from_cdev_locked(cdev);
1536 	if (IS_ERR(device)) {
1537 		DBF_EVENT_DEVID(DBF_DEBUG, cdev, "%s",
1538 				"unable to get device from cdev");
1539 		return;
1540 	}
1541 
1542 	if (!cqr->startdev ||
1543 	    device != cqr->startdev ||
1544 	    strncmp(cqr->startdev->discipline->ebcname,
1545 		    (char *) &cqr->magic, 4)) {
1546 		DBF_EVENT_DEVID(DBF_DEBUG, cdev, "%s",
1547 				"invalid device in request");
1548 		dasd_put_device(device);
1549 		return;
1550 	}
1551 
1552 	/* Schedule request to be retried. */
1553 	cqr->status = DASD_CQR_QUEUED;
1554 
1555 	dasd_device_clear_timer(device);
1556 	dasd_schedule_device_bh(device);
1557 	dasd_put_device(device);
1558 }
1559 
1560 void dasd_generic_handle_state_change(struct dasd_device *device)
1561 {
1562 	/* First of all start sense subsystem status request. */
1563 	dasd_eer_snss(device);
1564 
1565 	dasd_device_remove_stop_bits(device, DASD_STOPPED_PENDING);
1566 	dasd_schedule_device_bh(device);
1567 	if (device->block) {
1568 		dasd_schedule_block_bh(device->block);
1569 		if (device->block->gdp)
1570 			blk_mq_run_hw_queues(device->block->gdp->queue, true);
1571 	}
1572 }
1573 EXPORT_SYMBOL_GPL(dasd_generic_handle_state_change);
1574 
1575 static int dasd_check_hpf_error(struct irb *irb)
1576 {
1577 	return (scsw_tm_is_valid_schxs(&irb->scsw) &&
1578 	    (irb->scsw.tm.sesq == SCSW_SESQ_DEV_NOFCX ||
1579 	     irb->scsw.tm.sesq == SCSW_SESQ_PATH_NOFCX));
1580 }
1581 
1582 static int dasd_ese_needs_format(struct dasd_block *block, struct irb *irb)
1583 {
1584 	struct dasd_device *device = NULL;
1585 	u8 *sense = NULL;
1586 
1587 	if (!block)
1588 		return 0;
1589 	device = block->base;
1590 	if (!device || !device->discipline->is_ese)
1591 		return 0;
1592 	if (!device->discipline->is_ese(device))
1593 		return 0;
1594 
1595 	sense = dasd_get_sense(irb);
1596 	if (!sense)
1597 		return 0;
1598 
1599 	if (sense[1] & SNS1_NO_REC_FOUND)
1600 		return 1;
1601 
1602 	if ((sense[1] & SNS1_INV_TRACK_FORMAT) &&
1603 	    scsw_is_tm(&irb->scsw) &&
1604 	    !(sense[2] & SNS2_ENV_DATA_PRESENT))
1605 		return 1;
1606 
1607 	return 0;
1608 }
1609 
1610 static int dasd_ese_oos_cond(u8 *sense)
1611 {
1612 	return sense[0] & SNS0_EQUIPMENT_CHECK &&
1613 		sense[1] & SNS1_PERM_ERR &&
1614 		sense[1] & SNS1_WRITE_INHIBITED &&
1615 		sense[25] == 0x01;
1616 }
1617 
1618 /*
1619  * Interrupt handler for "normal" ssch-io based dasd devices.
1620  */
1621 void dasd_int_handler(struct ccw_device *cdev, unsigned long intparm,
1622 		      struct irb *irb)
1623 {
1624 	struct dasd_ccw_req *cqr, *next;
1625 	struct dasd_device *device;
1626 	unsigned long now;
1627 	int nrf_suppressed = 0;
1628 	int it_suppressed = 0;
1629 	struct request *req;
1630 	u8 *sense = NULL;
1631 	int expires;
1632 
1633 	cqr = (struct dasd_ccw_req *) intparm;
1634 	if (IS_ERR(irb)) {
1635 		switch (PTR_ERR(irb)) {
1636 		case -EIO:
1637 			if (cqr && cqr->status == DASD_CQR_CLEAR_PENDING) {
1638 				device = cqr->startdev;
1639 				cqr->status = DASD_CQR_CLEARED;
1640 				dasd_device_clear_timer(device);
1641 				wake_up(&dasd_flush_wq);
1642 				dasd_schedule_device_bh(device);
1643 				return;
1644 			}
1645 			break;
1646 		case -ETIMEDOUT:
1647 			DBF_EVENT_DEVID(DBF_WARNING, cdev, "%s: "
1648 					"request timed out\n", __func__);
1649 			break;
1650 		default:
1651 			DBF_EVENT_DEVID(DBF_WARNING, cdev, "%s: "
1652 					"unknown error %ld\n", __func__,
1653 					PTR_ERR(irb));
1654 		}
1655 		dasd_handle_killed_request(cdev, intparm);
1656 		return;
1657 	}
1658 
1659 	now = get_tod_clock();
1660 	/* check for conditions that should be handled immediately */
1661 	if (!cqr ||
1662 	    !(scsw_dstat(&irb->scsw) == (DEV_STAT_CHN_END | DEV_STAT_DEV_END) &&
1663 	      scsw_cstat(&irb->scsw) == 0)) {
1664 		if (cqr)
1665 			memcpy(&cqr->irb, irb, sizeof(*irb));
1666 		device = dasd_device_from_cdev_locked(cdev);
1667 		if (IS_ERR(device))
1668 			return;
1669 		/* ignore unsolicited interrupts for DIAG discipline */
1670 		if (device->discipline == dasd_diag_discipline_pointer) {
1671 			dasd_put_device(device);
1672 			return;
1673 		}
1674 
1675 		/*
1676 		 * In some cases 'File Protected' or 'No Record Found' errors
1677 		 * might be expected and debug log messages for the
1678 		 * corresponding interrupts shouldn't be written then.
1679 		 * Check if either of the according suppress bits is set.
1680 		 */
1681 		sense = dasd_get_sense(irb);
1682 		if (sense) {
1683 			it_suppressed =	(sense[1] & SNS1_INV_TRACK_FORMAT) &&
1684 				!(sense[2] & SNS2_ENV_DATA_PRESENT) &&
1685 				test_bit(DASD_CQR_SUPPRESS_IT, &cqr->flags);
1686 			nrf_suppressed = (sense[1] & SNS1_NO_REC_FOUND) &&
1687 				test_bit(DASD_CQR_SUPPRESS_NRF, &cqr->flags);
1688 
1689 			/*
1690 			 * Extent pool probably out-of-space.
1691 			 * Stop device and check exhaust level.
1692 			 */
1693 			if (dasd_ese_oos_cond(sense)) {
1694 				dasd_generic_space_exhaust(device, cqr);
1695 				device->discipline->ext_pool_exhaust(device, cqr);
1696 				dasd_put_device(device);
1697 				return;
1698 			}
1699 		}
1700 		if (!(it_suppressed || nrf_suppressed))
1701 			device->discipline->dump_sense_dbf(device, irb, "int");
1702 
1703 		if (device->features & DASD_FEATURE_ERPLOG)
1704 			device->discipline->dump_sense(device, cqr, irb);
1705 		device->discipline->check_for_device_change(device, cqr, irb);
1706 		dasd_put_device(device);
1707 	}
1708 
1709 	/* check for attention message */
1710 	if (scsw_dstat(&irb->scsw) & DEV_STAT_ATTENTION) {
1711 		device = dasd_device_from_cdev_locked(cdev);
1712 		if (!IS_ERR(device)) {
1713 			device->discipline->check_attention(device,
1714 							    irb->esw.esw1.lpum);
1715 			dasd_put_device(device);
1716 		}
1717 	}
1718 
1719 	if (!cqr)
1720 		return;
1721 
1722 	device = (struct dasd_device *) cqr->startdev;
1723 	if (!device ||
1724 	    strncmp(device->discipline->ebcname, (char *) &cqr->magic, 4)) {
1725 		DBF_EVENT_DEVID(DBF_DEBUG, cdev, "%s",
1726 				"invalid device in request");
1727 		return;
1728 	}
1729 
1730 	if (dasd_ese_needs_format(cqr->block, irb)) {
1731 		req = dasd_get_callback_data(cqr);
1732 		if (!req) {
1733 			cqr->status = DASD_CQR_ERROR;
1734 			return;
1735 		}
1736 		if (rq_data_dir(req) == READ) {
1737 			if (device->discipline->ese_read(cqr, irb))
1738 				cqr->status = DASD_CQR_ERROR;
1739 			else
1740 				cqr->status = DASD_CQR_SUCCESS;
1741 			cqr->stopclk = now;
1742 			dasd_device_clear_timer(device);
1743 			dasd_schedule_device_bh(device);
1744 			return;
1745 		}
1746 		if (cqr->filldata) {
1747 			/*
1748 			 * A WRITE_FULL_TRACK cqr carries the complete
1749 			 * track image; INV_TRACK_FORMAT here means the
1750 			 * generated image or the media itself is bad, not
1751 			 * that the track still needs formatting - retrying
1752 			 * via ese_format() would just resubmit the same
1753 			 * write. Let it fail instead.
1754 			 */
1755 			cqr->status = DASD_CQR_ERROR;
1756 			cqr->stopclk = now;
1757 			dasd_device_clear_timer(device);
1758 			dasd_schedule_device_bh(device);
1759 			return;
1760 		}
1761 		device->discipline->ese_format(device, cqr, irb);
1762 		return;
1763 	}
1764 
1765 	/* Check for clear pending */
1766 	if (cqr->status == DASD_CQR_CLEAR_PENDING &&
1767 	    scsw_fctl(&irb->scsw) & SCSW_FCTL_CLEAR_FUNC) {
1768 		cqr->status = DASD_CQR_CLEARED;
1769 		dasd_device_clear_timer(device);
1770 		wake_up(&dasd_flush_wq);
1771 		dasd_schedule_device_bh(device);
1772 		return;
1773 	}
1774 
1775 	/* check status - the request might have been killed by dyn detach */
1776 	if (cqr->status != DASD_CQR_IN_IO) {
1777 		DBF_DEV_EVENT(DBF_DEBUG, device, "invalid status: bus_id %s, "
1778 			      "status %02x", dev_name(&cdev->dev), cqr->status);
1779 		return;
1780 	}
1781 
1782 	next = NULL;
1783 	expires = 0;
1784 	if (scsw_dstat(&irb->scsw) == (DEV_STAT_CHN_END | DEV_STAT_DEV_END) &&
1785 	    scsw_cstat(&irb->scsw) == 0) {
1786 		/* request was completed successfully */
1787 		cqr->status = DASD_CQR_SUCCESS;
1788 		cqr->stopclk = now;
1789 		/* Start first request on queue if possible -> fast_io. */
1790 		if (cqr->devlist.next != &device->ccw_queue) {
1791 			next = list_entry(cqr->devlist.next,
1792 					  struct dasd_ccw_req, devlist);
1793 		}
1794 	} else {  /* error */
1795 		/* check for HPF error
1796 		 * call discipline function to requeue all requests
1797 		 * and disable HPF accordingly
1798 		 */
1799 		if (cqr->cpmode && dasd_check_hpf_error(irb) &&
1800 		    device->discipline->handle_hpf_error)
1801 			device->discipline->handle_hpf_error(device, irb);
1802 		/*
1803 		 * If we don't want complex ERP for this request, then just
1804 		 * reset this and retry it in the fastpath
1805 		 */
1806 		if (!test_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags) &&
1807 		    cqr->retries > 0) {
1808 			if (cqr->lpm == dasd_path_get_opm(device))
1809 				DBF_DEV_EVENT(DBF_DEBUG, device,
1810 					      "default ERP in fastpath "
1811 					      "(%i retries left)",
1812 					      cqr->retries);
1813 			if (!test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags))
1814 				cqr->lpm = dasd_path_get_opm(device);
1815 			cqr->status = DASD_CQR_QUEUED;
1816 			next = cqr;
1817 		} else
1818 			cqr->status = DASD_CQR_ERROR;
1819 	}
1820 	if (next && (next->status == DASD_CQR_QUEUED) &&
1821 	    (!device->stopped)) {
1822 		if (device->discipline->start_IO(next) == 0)
1823 			expires = next->expires;
1824 	}
1825 	if (expires != 0)
1826 		dasd_device_set_timer(device, expires);
1827 	else
1828 		dasd_device_clear_timer(device);
1829 	dasd_schedule_device_bh(device);
1830 }
1831 EXPORT_SYMBOL(dasd_int_handler);
1832 
1833 enum uc_todo dasd_generic_uc_handler(struct ccw_device *cdev, struct irb *irb)
1834 {
1835 	struct dasd_device *device;
1836 
1837 	device = dasd_device_from_cdev_locked(cdev);
1838 
1839 	if (IS_ERR(device))
1840 		goto out;
1841 	if (test_bit(DASD_FLAG_OFFLINE, &device->flags) ||
1842 	   device->state != device->target ||
1843 	   !device->discipline->check_for_device_change){
1844 		dasd_put_device(device);
1845 		goto out;
1846 	}
1847 	if (device->discipline->dump_sense_dbf)
1848 		device->discipline->dump_sense_dbf(device, irb, "uc");
1849 	device->discipline->check_for_device_change(device, NULL, irb);
1850 	dasd_put_device(device);
1851 out:
1852 	return UC_TODO_RETRY;
1853 }
1854 EXPORT_SYMBOL_GPL(dasd_generic_uc_handler);
1855 
1856 /*
1857  * If we have an error on a dasd_block layer request then we cancel
1858  * and return all further requests from the same dasd_block as well.
1859  */
1860 static void __dasd_device_recovery(struct dasd_device *device,
1861 				   struct dasd_ccw_req *ref_cqr)
1862 {
1863 	struct list_head *l, *n;
1864 	struct dasd_ccw_req *cqr;
1865 
1866 	/*
1867 	 * only requeue request that came from the dasd_block layer
1868 	 */
1869 	if (!ref_cqr->block)
1870 		return;
1871 
1872 	list_for_each_safe(l, n, &device->ccw_queue) {
1873 		cqr = list_entry(l, struct dasd_ccw_req, devlist);
1874 		if (cqr->status == DASD_CQR_QUEUED &&
1875 		    ref_cqr->block == cqr->block) {
1876 			cqr->status = DASD_CQR_CLEARED;
1877 		}
1878 	}
1879 };
1880 
1881 /*
1882  * Remove those ccw requests from the queue that need to be returned
1883  * to the upper layer.
1884  */
1885 static void __dasd_device_process_ccw_queue(struct dasd_device *device,
1886 					    struct list_head *final_queue)
1887 {
1888 	struct list_head *l, *n;
1889 	struct dasd_ccw_req *cqr;
1890 
1891 	/* Process request with final status. */
1892 	list_for_each_safe(l, n, &device->ccw_queue) {
1893 		cqr = list_entry(l, struct dasd_ccw_req, devlist);
1894 
1895 		/* Skip any non-final request. */
1896 		if (cqr->status == DASD_CQR_QUEUED ||
1897 		    cqr->status == DASD_CQR_IN_IO ||
1898 		    cqr->status == DASD_CQR_CLEAR_PENDING)
1899 			continue;
1900 		if (cqr->status == DASD_CQR_ERROR) {
1901 			__dasd_device_recovery(device, cqr);
1902 		}
1903 		/* Rechain finished requests to final queue */
1904 		list_move_tail(&cqr->devlist, final_queue);
1905 	}
1906 }
1907 
1908 static void __dasd_process_cqr(struct dasd_device *device,
1909 			       struct dasd_ccw_req *cqr)
1910 {
1911 	switch (cqr->status) {
1912 	case DASD_CQR_SUCCESS:
1913 		cqr->status = DASD_CQR_DONE;
1914 		break;
1915 	case DASD_CQR_ERROR:
1916 		cqr->status = DASD_CQR_NEED_ERP;
1917 		break;
1918 	case DASD_CQR_CLEARED:
1919 		cqr->status = DASD_CQR_TERMINATED;
1920 		break;
1921 	case DASD_CQR_ABORT:
1922 		cqr->status = DASD_CQR_ABORTED;
1923 		/*
1924 		 * ABORT is only set on the block-layer origin write that a
1925 		 * full-track format replaces. Clear the callback so the request
1926 		 * is not completed here - the replacement completes it. Internal
1927 		 * requests never take this path, so no sleep_on waiter is left
1928 		 * without its wakeup.
1929 		 */
1930 		cqr->callback = NULL;
1931 		break;
1932 	default:
1933 		dev_err(&device->cdev->dev,
1934 			"Unexpected CQR status %02x", cqr->status);
1935 		BUG();
1936 	}
1937 	if (cqr->callback)
1938 		cqr->callback(cqr, cqr->callback_data);
1939 }
1940 
1941 /*
1942  * the cqrs from the final queue are returned to the upper layer
1943  * by setting a dasd_block state and calling the callback function
1944  */
1945 static void __dasd_device_process_final_queue(struct dasd_device *device,
1946 					      struct list_head *final_queue)
1947 {
1948 	struct list_head *l, *n;
1949 	struct dasd_ccw_req *cqr;
1950 	struct dasd_block *block;
1951 
1952 	list_for_each_safe(l, n, final_queue) {
1953 		cqr = list_entry(l, struct dasd_ccw_req, devlist);
1954 		list_del_init(&cqr->devlist);
1955 		block = cqr->block;
1956 		if (!block) {
1957 			__dasd_process_cqr(device, cqr);
1958 		} else {
1959 			spin_lock_bh(&block->queue_lock);
1960 			__dasd_process_cqr(device, cqr);
1961 			spin_unlock_bh(&block->queue_lock);
1962 		}
1963 	}
1964 }
1965 
1966 /*
1967  * check if device should be autoquiesced due to too many timeouts
1968  */
1969 static void __dasd_device_check_autoquiesce_timeout(struct dasd_device *device,
1970 						    struct dasd_ccw_req *cqr)
1971 {
1972 	if ((device->default_retries - cqr->retries) >= device->aq_timeouts)
1973 		dasd_handle_autoquiesce(device, cqr, DASD_EER_TIMEOUTS);
1974 }
1975 
1976 /*
1977  * Take a look at the first request on the ccw queue and check
1978  * if it reached its expire time. If so, terminate the IO.
1979  */
1980 static void __dasd_device_check_expire(struct dasd_device *device)
1981 {
1982 	struct dasd_ccw_req *cqr;
1983 
1984 	if (list_empty(&device->ccw_queue))
1985 		return;
1986 	cqr = list_entry(device->ccw_queue.next, struct dasd_ccw_req, devlist);
1987 	if ((cqr->status == DASD_CQR_IN_IO && cqr->expires != 0) &&
1988 	    (time_after_eq(jiffies, cqr->expires + cqr->starttime))) {
1989 		if (test_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
1990 			/*
1991 			 * IO in safe offline processing should not
1992 			 * run out of retries
1993 			 */
1994 			cqr->retries++;
1995 		}
1996 		if (device->discipline->term_IO(cqr) != 0) {
1997 			/* Hmpf, try again in 5 sec */
1998 			dev_err(&device->cdev->dev,
1999 				"CQR timed out (%lus) but cannot be ended, retrying in 5s\n",
2000 				(cqr->expires / HZ));
2001 			cqr->expires += 5*HZ;
2002 			dasd_device_set_timer(device, 5*HZ);
2003 		} else {
2004 			dev_err(&device->cdev->dev,
2005 				"CQR timed out (%lus), %i retries remaining\n",
2006 				(cqr->expires / HZ), cqr->retries);
2007 		}
2008 		__dasd_device_check_autoquiesce_timeout(device, cqr);
2009 	}
2010 }
2011 
2012 /*
2013  * return 1 when device is not eligible for IO
2014  */
2015 static int __dasd_device_is_unusable(struct dasd_device *device,
2016 				     struct dasd_ccw_req *cqr)
2017 {
2018 	int mask = ~(DASD_STOPPED_DC_WAIT | DASD_STOPPED_NOSPC);
2019 
2020 	if (test_bit(DASD_FLAG_OFFLINE, &device->flags) &&
2021 	    !test_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
2022 		/*
2023 		 * dasd is being set offline
2024 		 * but it is no safe offline where we have to allow I/O
2025 		 */
2026 		return 1;
2027 	}
2028 	if (device->stopped) {
2029 		if (device->stopped & mask) {
2030 			/* stopped and CQR will not change that. */
2031 			return 1;
2032 		}
2033 		if (!test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags)) {
2034 			/* CQR is not able to change device to
2035 			 * operational. */
2036 			return 1;
2037 		}
2038 		/* CQR required to get device operational. */
2039 	}
2040 	return 0;
2041 }
2042 
2043 /*
2044  * Take a look at the first request on the ccw queue and check
2045  * if it needs to be started.
2046  */
2047 static void __dasd_device_start_head(struct dasd_device *device)
2048 {
2049 	struct dasd_ccw_req *cqr;
2050 	int rc;
2051 
2052 	if (list_empty(&device->ccw_queue))
2053 		return;
2054 	cqr = list_entry(device->ccw_queue.next, struct dasd_ccw_req, devlist);
2055 	if (cqr->status != DASD_CQR_QUEUED)
2056 		return;
2057 	/* if device is not usable return request to upper layer */
2058 	if (__dasd_device_is_unusable(device, cqr)) {
2059 		cqr->intrc = -EAGAIN;
2060 		cqr->status = DASD_CQR_CLEARED;
2061 		dasd_schedule_device_bh(device);
2062 		return;
2063 	}
2064 
2065 	rc = device->discipline->start_IO(cqr);
2066 	if (rc == 0)
2067 		dasd_device_set_timer(device, cqr->expires);
2068 	else if (rc == -EACCES) {
2069 		dasd_schedule_device_bh(device);
2070 	} else
2071 		/* Hmpf, try again in 1/2 sec */
2072 		dasd_device_set_timer(device, 50);
2073 }
2074 
2075 static void __dasd_device_check_path_events(struct dasd_device *device)
2076 {
2077 	__u8 tbvpm, fcsecpm;
2078 	int rc;
2079 
2080 	tbvpm = dasd_path_get_tbvpm(device);
2081 	fcsecpm = dasd_path_get_fcsecpm(device);
2082 
2083 	if (!tbvpm && !fcsecpm)
2084 		return;
2085 
2086 	if (device->stopped & ~(DASD_STOPPED_DC_WAIT))
2087 		return;
2088 
2089 	dasd_path_clear_all_verify(device);
2090 	dasd_path_clear_all_fcsec(device);
2091 
2092 	rc = device->discipline->pe_handler(device, tbvpm, fcsecpm);
2093 	if (rc) {
2094 		dasd_path_add_tbvpm(device, tbvpm);
2095 		dasd_path_add_fcsecpm(device, fcsecpm);
2096 		dasd_device_set_timer(device, 50);
2097 	}
2098 };
2099 
2100 /*
2101  * Go through all request on the dasd_device request queue,
2102  * terminate them on the cdev if necessary, and return them to the
2103  * submitting layer via callback.
2104  * Note:
2105  * Make sure that all 'submitting layers' still exist when
2106  * this function is called!. In other words, when 'device' is a base
2107  * device then all block layer requests must have been removed before
2108  * via dasd_flush_block_queue.
2109  */
2110 int dasd_flush_device_queue(struct dasd_device *device)
2111 {
2112 	struct dasd_ccw_req *cqr, *n;
2113 	int rc;
2114 	struct list_head flush_queue;
2115 
2116 	INIT_LIST_HEAD(&flush_queue);
2117 	spin_lock_irq(get_ccwdev_lock(device->cdev));
2118 	rc = 0;
2119 	list_for_each_entry_safe(cqr, n, &device->ccw_queue, devlist) {
2120 		/* Check status and move request to flush_queue */
2121 		switch (cqr->status) {
2122 		case DASD_CQR_IN_IO:
2123 			rc = device->discipline->term_IO(cqr);
2124 			if (rc) {
2125 				/* unable to terminate request */
2126 				dev_err(&device->cdev->dev,
2127 					"Flushing the DASD request queue failed\n");
2128 				/* stop flush processing */
2129 				goto finished;
2130 			}
2131 			break;
2132 		case DASD_CQR_QUEUED:
2133 			cqr->stopclk = get_tod_clock();
2134 			cqr->status = DASD_CQR_CLEARED;
2135 			break;
2136 		default: /* no need to modify the others */
2137 			break;
2138 		}
2139 		list_move_tail(&cqr->devlist, &flush_queue);
2140 	}
2141 finished:
2142 	spin_unlock_irq(get_ccwdev_lock(device->cdev));
2143 	/*
2144 	 * After this point all requests must be in state CLEAR_PENDING,
2145 	 * CLEARED, SUCCESS or ERROR. Now wait for CLEAR_PENDING to become
2146 	 * one of the others.
2147 	 */
2148 	list_for_each_entry_safe(cqr, n, &flush_queue, devlist)
2149 		wait_event(dasd_flush_wq,
2150 			   (cqr->status != DASD_CQR_CLEAR_PENDING));
2151 	/*
2152 	 * Now set each request back to TERMINATED, DONE or NEED_ERP
2153 	 * and call the callback function of flushed requests
2154 	 */
2155 	__dasd_device_process_final_queue(device, &flush_queue);
2156 	return rc;
2157 }
2158 EXPORT_SYMBOL_GPL(dasd_flush_device_queue);
2159 
2160 /*
2161  * Acquire the device lock and process queues for the device.
2162  */
2163 static void dasd_device_tasklet(unsigned long data)
2164 {
2165 	struct dasd_device *device = (struct dasd_device *) data;
2166 	struct list_head final_queue;
2167 
2168 	atomic_set (&device->tasklet_scheduled, 0);
2169 	INIT_LIST_HEAD(&final_queue);
2170 	spin_lock_irq(get_ccwdev_lock(device->cdev));
2171 	/* Check expire time of first request on the ccw queue. */
2172 	__dasd_device_check_expire(device);
2173 	/* find final requests on ccw queue */
2174 	__dasd_device_process_ccw_queue(device, &final_queue);
2175 	__dasd_device_check_path_events(device);
2176 	spin_unlock_irq(get_ccwdev_lock(device->cdev));
2177 	/* Now call the callback function of requests with final status */
2178 	__dasd_device_process_final_queue(device, &final_queue);
2179 	spin_lock_irq(get_ccwdev_lock(device->cdev));
2180 	/* Now check if the head of the ccw queue needs to be started. */
2181 	__dasd_device_start_head(device);
2182 	spin_unlock_irq(get_ccwdev_lock(device->cdev));
2183 	if (waitqueue_active(&shutdown_waitq))
2184 		wake_up(&shutdown_waitq);
2185 	dasd_put_device(device);
2186 }
2187 
2188 /*
2189  * Schedules a call to dasd_tasklet over the device tasklet.
2190  */
2191 void dasd_schedule_device_bh(struct dasd_device *device)
2192 {
2193 	/* Protect against rescheduling. */
2194 	if (atomic_cmpxchg (&device->tasklet_scheduled, 0, 1) != 0)
2195 		return;
2196 	dasd_get_device(device);
2197 	tasklet_hi_schedule(&device->tasklet);
2198 }
2199 EXPORT_SYMBOL(dasd_schedule_device_bh);
2200 
2201 void dasd_device_set_stop_bits(struct dasd_device *device, int bits)
2202 {
2203 	device->stopped |= bits;
2204 }
2205 EXPORT_SYMBOL_GPL(dasd_device_set_stop_bits);
2206 
2207 void dasd_device_remove_stop_bits(struct dasd_device *device, int bits)
2208 {
2209 	device->stopped &= ~bits;
2210 	if (!device->stopped)
2211 		wake_up(&generic_waitq);
2212 }
2213 EXPORT_SYMBOL_GPL(dasd_device_remove_stop_bits);
2214 
2215 /*
2216  * Queue a request to the head of the device ccw_queue.
2217  * Start the I/O if possible.
2218  */
2219 void dasd_add_request_head(struct dasd_ccw_req *cqr)
2220 {
2221 	struct dasd_device *device;
2222 	unsigned long flags;
2223 
2224 	device = cqr->startdev;
2225 	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
2226 	cqr->status = DASD_CQR_QUEUED;
2227 	list_add(&cqr->devlist, &device->ccw_queue);
2228 	/* let the bh start the request to keep them in order */
2229 	dasd_schedule_device_bh(device);
2230 	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
2231 }
2232 EXPORT_SYMBOL(dasd_add_request_head);
2233 
2234 /*
2235  * Queue a request to the tail of the device ccw_queue.
2236  * Start the I/O if possible.
2237  */
2238 void dasd_add_request_tail(struct dasd_ccw_req *cqr)
2239 {
2240 	struct dasd_device *device;
2241 	unsigned long flags;
2242 
2243 	device = cqr->startdev;
2244 	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
2245 	cqr->status = DASD_CQR_QUEUED;
2246 	list_add_tail(&cqr->devlist, &device->ccw_queue);
2247 	/* let the bh start the request to keep them in order */
2248 	dasd_schedule_device_bh(device);
2249 	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
2250 }
2251 EXPORT_SYMBOL(dasd_add_request_tail);
2252 
2253 /*
2254  * Wakeup helper for the 'sleep_on' functions.
2255  */
2256 void dasd_wakeup_cb(struct dasd_ccw_req *cqr, void *data)
2257 {
2258 	spin_lock_irq(get_ccwdev_lock(cqr->startdev->cdev));
2259 	cqr->endclk = get_tod_clock();
2260 	cqr->callback_data = DASD_SLEEPON_END_TAG;
2261 	spin_unlock_irq(get_ccwdev_lock(cqr->startdev->cdev));
2262 	wake_up(&generic_waitq);
2263 }
2264 EXPORT_SYMBOL_GPL(dasd_wakeup_cb);
2265 
2266 static inline int _wait_for_wakeup(struct dasd_ccw_req *cqr)
2267 {
2268 	struct dasd_device *device;
2269 	int rc;
2270 
2271 	device = cqr->startdev;
2272 	spin_lock_irq(get_ccwdev_lock(device->cdev));
2273 	rc = (cqr->callback_data == DASD_SLEEPON_END_TAG);
2274 	spin_unlock_irq(get_ccwdev_lock(device->cdev));
2275 	return rc;
2276 }
2277 
2278 /*
2279  * checks if error recovery is necessary, returns 1 if yes, 0 otherwise.
2280  */
2281 static int __dasd_sleep_on_erp(struct dasd_ccw_req *cqr)
2282 {
2283 	struct dasd_device *device;
2284 	dasd_erp_fn_t erp_fn;
2285 
2286 	if (cqr->status == DASD_CQR_FILLED)
2287 		return 0;
2288 	device = cqr->startdev;
2289 	if (test_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags)) {
2290 		if (cqr->status == DASD_CQR_TERMINATED) {
2291 			device->discipline->handle_terminated_request(cqr);
2292 			return 1;
2293 		}
2294 		if (cqr->status == DASD_CQR_NEED_ERP) {
2295 			erp_fn = device->discipline->erp_action(cqr);
2296 			erp_fn(cqr);
2297 			return 1;
2298 		}
2299 		if (cqr->status == DASD_CQR_FAILED)
2300 			dasd_log_sense(cqr, &cqr->irb);
2301 		if (cqr->refers) {
2302 			__dasd_process_erp(device, cqr);
2303 			return 1;
2304 		}
2305 	}
2306 	return 0;
2307 }
2308 
2309 static int __dasd_sleep_on_loop_condition(struct dasd_ccw_req *cqr)
2310 {
2311 	if (test_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags)) {
2312 		if (cqr->refers) /* erp is not done yet */
2313 			return 1;
2314 		return ((cqr->status != DASD_CQR_DONE) &&
2315 			(cqr->status != DASD_CQR_FAILED));
2316 	} else
2317 		return (cqr->status == DASD_CQR_FILLED);
2318 }
2319 
2320 static int _dasd_sleep_on(struct dasd_ccw_req *maincqr, int interruptible)
2321 {
2322 	struct dasd_device *device;
2323 	int rc;
2324 	struct list_head ccw_queue;
2325 	struct dasd_ccw_req *cqr;
2326 
2327 	INIT_LIST_HEAD(&ccw_queue);
2328 	maincqr->status = DASD_CQR_FILLED;
2329 	device = maincqr->startdev;
2330 	list_add(&maincqr->blocklist, &ccw_queue);
2331 	for (cqr = maincqr;  __dasd_sleep_on_loop_condition(cqr);
2332 	     cqr = list_first_entry(&ccw_queue,
2333 				    struct dasd_ccw_req, blocklist)) {
2334 
2335 		if (__dasd_sleep_on_erp(cqr))
2336 			continue;
2337 		if (cqr->status != DASD_CQR_FILLED) /* could be failed */
2338 			continue;
2339 		if (test_bit(DASD_FLAG_LOCK_STOLEN, &device->flags) &&
2340 		    !test_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags)) {
2341 			cqr->status = DASD_CQR_FAILED;
2342 			cqr->intrc = -EPERM;
2343 			continue;
2344 		}
2345 		/* Non-temporary stop condition will trigger fail fast */
2346 		if (device->stopped & ~DASD_STOPPED_PENDING &&
2347 		    test_bit(DASD_CQR_FLAGS_FAILFAST, &cqr->flags) &&
2348 		    !dasd_eer_enabled(device) && device->aq_mask == 0) {
2349 			cqr->status = DASD_CQR_FAILED;
2350 			cqr->intrc = -ENOLINK;
2351 			continue;
2352 		}
2353 		/*
2354 		 * Don't try to start requests if device is in
2355 		 * offline processing, it might wait forever
2356 		 */
2357 		if (test_bit(DASD_FLAG_OFFLINE, &device->flags)) {
2358 			cqr->status = DASD_CQR_FAILED;
2359 			cqr->intrc = -ENODEV;
2360 			continue;
2361 		}
2362 		/*
2363 		 * Don't try to start requests if device is stopped
2364 		 * except path verification requests
2365 		 */
2366 		if (!test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags)) {
2367 			if (interruptible) {
2368 				rc = wait_event_interruptible(
2369 					generic_waitq, !(device->stopped));
2370 				if (rc == -ERESTARTSYS) {
2371 					cqr->status = DASD_CQR_FAILED;
2372 					maincqr->intrc = rc;
2373 					continue;
2374 				}
2375 			} else
2376 				wait_event(generic_waitq, !(device->stopped));
2377 		}
2378 		if (!cqr->callback)
2379 			cqr->callback = dasd_wakeup_cb;
2380 
2381 		cqr->callback_data = DASD_SLEEPON_START_TAG;
2382 		dasd_add_request_tail(cqr);
2383 		if (interruptible) {
2384 			rc = wait_event_interruptible(
2385 				generic_waitq, _wait_for_wakeup(cqr));
2386 			if (rc == -ERESTARTSYS) {
2387 				dasd_cancel_req(cqr);
2388 				/* wait (non-interruptible) for final status */
2389 				wait_event(generic_waitq,
2390 					   _wait_for_wakeup(cqr));
2391 				cqr->status = DASD_CQR_FAILED;
2392 				maincqr->intrc = rc;
2393 				continue;
2394 			}
2395 		} else
2396 			wait_event(generic_waitq, _wait_for_wakeup(cqr));
2397 	}
2398 
2399 	maincqr->endclk = get_tod_clock();
2400 	if ((maincqr->status != DASD_CQR_DONE) &&
2401 	    (maincqr->intrc != -ERESTARTSYS))
2402 		dasd_log_sense(maincqr, &maincqr->irb);
2403 	if (maincqr->status == DASD_CQR_DONE)
2404 		rc = 0;
2405 	else if (maincqr->intrc)
2406 		rc = maincqr->intrc;
2407 	else
2408 		rc = -EIO;
2409 	return rc;
2410 }
2411 
2412 static inline int _wait_for_wakeup_queue(struct list_head *ccw_queue)
2413 {
2414 	struct dasd_ccw_req *cqr;
2415 
2416 	list_for_each_entry(cqr, ccw_queue, blocklist) {
2417 		if (cqr->callback_data != DASD_SLEEPON_END_TAG)
2418 			return 0;
2419 	}
2420 
2421 	return 1;
2422 }
2423 
2424 static int _dasd_sleep_on_queue(struct list_head *ccw_queue, int interruptible)
2425 {
2426 	struct dasd_device *device;
2427 	struct dasd_ccw_req *cqr, *n;
2428 	u8 *sense = NULL;
2429 	int rc;
2430 
2431 retry:
2432 	list_for_each_entry_safe(cqr, n, ccw_queue, blocklist) {
2433 		device = cqr->startdev;
2434 		if (cqr->status != DASD_CQR_FILLED) /*could be failed*/
2435 			continue;
2436 
2437 		if (test_bit(DASD_FLAG_LOCK_STOLEN, &device->flags) &&
2438 		    !test_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags)) {
2439 			cqr->status = DASD_CQR_FAILED;
2440 			cqr->intrc = -EPERM;
2441 			continue;
2442 		}
2443 		/*Non-temporary stop condition will trigger fail fast*/
2444 		if (device->stopped & ~DASD_STOPPED_PENDING &&
2445 		    test_bit(DASD_CQR_FLAGS_FAILFAST, &cqr->flags) &&
2446 		    !dasd_eer_enabled(device)) {
2447 			cqr->status = DASD_CQR_FAILED;
2448 			cqr->intrc = -EAGAIN;
2449 			continue;
2450 		}
2451 
2452 		/*Don't try to start requests if device is stopped*/
2453 		if (interruptible) {
2454 			rc = wait_event_interruptible(
2455 				generic_waitq, !device->stopped);
2456 			if (rc == -ERESTARTSYS) {
2457 				cqr->status = DASD_CQR_FAILED;
2458 				cqr->intrc = rc;
2459 				continue;
2460 			}
2461 		} else
2462 			wait_event(generic_waitq, !(device->stopped));
2463 
2464 		if (!cqr->callback)
2465 			cqr->callback = dasd_wakeup_cb;
2466 		cqr->callback_data = DASD_SLEEPON_START_TAG;
2467 		dasd_add_request_tail(cqr);
2468 	}
2469 
2470 	wait_event(generic_waitq, _wait_for_wakeup_queue(ccw_queue));
2471 
2472 	rc = 0;
2473 	list_for_each_entry_safe(cqr, n, ccw_queue, blocklist) {
2474 		/*
2475 		 * In some cases certain errors might be expected and
2476 		 * error recovery would be unnecessary in these cases.
2477 		 * Check if the according suppress bit is set.
2478 		 */
2479 		sense = dasd_get_sense(&cqr->irb);
2480 		if (sense && (sense[1] & SNS1_INV_TRACK_FORMAT) &&
2481 		    !(sense[2] & SNS2_ENV_DATA_PRESENT) &&
2482 		    test_bit(DASD_CQR_SUPPRESS_IT, &cqr->flags))
2483 			continue;
2484 		if (sense && (sense[1] & SNS1_NO_REC_FOUND) &&
2485 		    test_bit(DASD_CQR_SUPPRESS_NRF, &cqr->flags))
2486 			continue;
2487 		if (scsw_cstat(&cqr->irb.scsw) == 0x40 &&
2488 		    test_bit(DASD_CQR_SUPPRESS_IL, &cqr->flags))
2489 			continue;
2490 
2491 		/*
2492 		 * for alias devices simplify error recovery and
2493 		 * return to upper layer
2494 		 * do not skip ERP requests
2495 		 */
2496 		if (cqr->startdev != cqr->basedev && !cqr->refers &&
2497 		    (cqr->status == DASD_CQR_TERMINATED ||
2498 		     cqr->status == DASD_CQR_NEED_ERP))
2499 			return -EAGAIN;
2500 
2501 		/* normal recovery for basedev IO */
2502 		if (__dasd_sleep_on_erp(cqr))
2503 			/* handle erp first */
2504 			goto retry;
2505 	}
2506 
2507 	return 0;
2508 }
2509 
2510 /*
2511  * Queue a request to the tail of the device ccw_queue and wait for
2512  * it's completion.
2513  */
2514 int dasd_sleep_on(struct dasd_ccw_req *cqr)
2515 {
2516 	return _dasd_sleep_on(cqr, 0);
2517 }
2518 EXPORT_SYMBOL(dasd_sleep_on);
2519 
2520 /*
2521  * Start requests from a ccw_queue and wait for their completion.
2522  */
2523 int dasd_sleep_on_queue(struct list_head *ccw_queue)
2524 {
2525 	return _dasd_sleep_on_queue(ccw_queue, 0);
2526 }
2527 EXPORT_SYMBOL(dasd_sleep_on_queue);
2528 
2529 /*
2530  * Start requests from a ccw_queue and wait interruptible for their completion.
2531  */
2532 int dasd_sleep_on_queue_interruptible(struct list_head *ccw_queue)
2533 {
2534 	return _dasd_sleep_on_queue(ccw_queue, 1);
2535 }
2536 EXPORT_SYMBOL(dasd_sleep_on_queue_interruptible);
2537 
2538 /*
2539  * Queue a request to the tail of the device ccw_queue and wait
2540  * interruptible for it's completion.
2541  */
2542 int dasd_sleep_on_interruptible(struct dasd_ccw_req *cqr)
2543 {
2544 	return _dasd_sleep_on(cqr, 1);
2545 }
2546 EXPORT_SYMBOL(dasd_sleep_on_interruptible);
2547 
2548 /*
2549  * Whoa nelly now it gets really hairy. For some functions (e.g. steal lock
2550  * for eckd devices) the currently running request has to be terminated
2551  * and be put back to status queued, before the special request is added
2552  * to the head of the queue. Then the special request is waited on normally.
2553  */
2554 static inline int _dasd_term_running_cqr(struct dasd_device *device)
2555 {
2556 	struct dasd_ccw_req *cqr;
2557 	int rc;
2558 
2559 	if (list_empty(&device->ccw_queue))
2560 		return 0;
2561 	cqr = list_entry(device->ccw_queue.next, struct dasd_ccw_req, devlist);
2562 	/*
2563 	 * Path verification requests must not be terminated. They are critical
2564 	 * for bringing paths back online. Terminating them would cause rc=-EIO
2565 	 * because CLEARED requests skip the retry path.
2566 	 */
2567 	if (test_bit(DASD_CQR_VERIFY_PATH, &cqr->flags))
2568 		return -EAGAIN;
2569 	rc = device->discipline->term_IO(cqr);
2570 	if (!rc)
2571 		/*
2572 		 * CQR terminated because a more important request is pending.
2573 		 * Undo decreasing of retry counter because this is
2574 		 * not an error case.
2575 		 */
2576 		cqr->retries++;
2577 	return rc;
2578 }
2579 
2580 int dasd_sleep_on_immediately(struct dasd_ccw_req *cqr)
2581 {
2582 	struct dasd_device *device;
2583 	int rc;
2584 
2585 	device = cqr->startdev;
2586 	if (test_bit(DASD_FLAG_LOCK_STOLEN, &device->flags) &&
2587 	    !test_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags)) {
2588 		cqr->status = DASD_CQR_FAILED;
2589 		cqr->intrc = -EPERM;
2590 		return -EIO;
2591 	}
2592 	spin_lock_irq(get_ccwdev_lock(device->cdev));
2593 	while ((rc = _dasd_term_running_cqr(device)) == -EAGAIN) {
2594 		spin_unlock_irq(get_ccwdev_lock(device->cdev));
2595 		msleep(1);
2596 		spin_lock_irq(get_ccwdev_lock(device->cdev));
2597 	}
2598 	if (rc) {
2599 		spin_unlock_irq(get_ccwdev_lock(device->cdev));
2600 		return rc;
2601 	}
2602 	cqr->callback = dasd_wakeup_cb;
2603 	cqr->callback_data = DASD_SLEEPON_START_TAG;
2604 	cqr->status = DASD_CQR_QUEUED;
2605 	/*
2606 	 * add new request as second
2607 	 * first the terminated cqr needs to be finished
2608 	 */
2609 	list_add(&cqr->devlist, device->ccw_queue.next);
2610 
2611 	/* let the bh start the request to keep them in order */
2612 	dasd_schedule_device_bh(device);
2613 
2614 	spin_unlock_irq(get_ccwdev_lock(device->cdev));
2615 
2616 	wait_event(generic_waitq, _wait_for_wakeup(cqr));
2617 
2618 	if (cqr->status == DASD_CQR_DONE)
2619 		rc = 0;
2620 	else if (cqr->intrc)
2621 		rc = cqr->intrc;
2622 	else
2623 		rc = -EIO;
2624 
2625 	/* kick tasklets */
2626 	dasd_schedule_device_bh(device);
2627 	if (device->block)
2628 		dasd_schedule_block_bh(device->block);
2629 
2630 	return rc;
2631 }
2632 EXPORT_SYMBOL(dasd_sleep_on_immediately);
2633 
2634 /*
2635  * Cancels a request that was started with dasd_sleep_on_req.
2636  * This is useful to timeout requests. The request will be
2637  * terminated if it is currently in i/o.
2638  * Returns 0 if request termination was successful
2639  *	   negative error code if termination failed
2640  * Cancellation of a request is an asynchronous operation! The calling
2641  * function has to wait until the request is properly returned via callback.
2642  */
2643 static int __dasd_cancel_req(struct dasd_ccw_req *cqr)
2644 {
2645 	struct dasd_device *device = cqr->startdev;
2646 	int rc = 0;
2647 
2648 	switch (cqr->status) {
2649 	case DASD_CQR_QUEUED:
2650 		/* request was not started - just set to cleared */
2651 		cqr->status = DASD_CQR_CLEARED;
2652 		break;
2653 	case DASD_CQR_IN_IO:
2654 		/* request in IO - terminate IO and release again */
2655 		rc = device->discipline->term_IO(cqr);
2656 		if (rc) {
2657 			dev_err(&device->cdev->dev,
2658 				"Cancelling request failed with rc=%d\n", rc);
2659 		} else {
2660 			cqr->stopclk = get_tod_clock();
2661 		}
2662 		break;
2663 	default: /* already finished or clear pending - do nothing */
2664 		break;
2665 	}
2666 	dasd_schedule_device_bh(device);
2667 	return rc;
2668 }
2669 
2670 int dasd_cancel_req(struct dasd_ccw_req *cqr)
2671 {
2672 	struct dasd_device *device = cqr->startdev;
2673 	unsigned long flags;
2674 	int rc;
2675 
2676 	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
2677 	rc = __dasd_cancel_req(cqr);
2678 	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
2679 	return rc;
2680 }
2681 
2682 /*
2683  * SECTION: Operations of the dasd_block layer.
2684  */
2685 
2686 /*
2687  * Timeout function for dasd_block. This is used when the block layer
2688  * is waiting for something that may not come reliably, (e.g. a state
2689  * change interrupt)
2690  */
2691 static void dasd_block_timeout(struct timer_list *t)
2692 {
2693 	unsigned long flags;
2694 	struct dasd_block *block;
2695 
2696 	block = timer_container_of(block, t, timer);
2697 	spin_lock_irqsave(get_ccwdev_lock(block->base->cdev), flags);
2698 	/* re-activate request queue */
2699 	dasd_device_remove_stop_bits(block->base, DASD_STOPPED_PENDING);
2700 	spin_unlock_irqrestore(get_ccwdev_lock(block->base->cdev), flags);
2701 	dasd_schedule_block_bh(block);
2702 	blk_mq_run_hw_queues(block->gdp->queue, true);
2703 }
2704 
2705 /*
2706  * Setup timeout for a dasd_block in jiffies.
2707  */
2708 void dasd_block_set_timer(struct dasd_block *block, int expires)
2709 {
2710 	if (expires == 0)
2711 		timer_delete(&block->timer);
2712 	else
2713 		mod_timer(&block->timer, jiffies + expires);
2714 }
2715 EXPORT_SYMBOL(dasd_block_set_timer);
2716 
2717 /*
2718  * Clear timeout for a dasd_block.
2719  */
2720 void dasd_block_clear_timer(struct dasd_block *block)
2721 {
2722 	timer_delete(&block->timer);
2723 }
2724 EXPORT_SYMBOL(dasd_block_clear_timer);
2725 
2726 /*
2727  * Process finished error recovery ccw.
2728  */
2729 static void __dasd_process_erp(struct dasd_device *device,
2730 			       struct dasd_ccw_req *cqr)
2731 {
2732 	dasd_erp_fn_t erp_fn;
2733 
2734 	if (cqr->status == DASD_CQR_DONE)
2735 		DBF_DEV_EVENT(DBF_NOTICE, device, "%s", "ERP successful");
2736 	else if (cqr->status == DASD_CQR_ABORTED)
2737 		/*
2738 		 * ESE format aborts the request and replaces it with a format
2739 		 * CQR - this is not an ERP failure.
2740 		 */
2741 		DBF_DEV_EVENT(DBF_NOTICE, device, "%s",
2742 			      "ERP request aborted, replaced by ESE format");
2743 	else
2744 		dev_err(&device->cdev->dev, "ERP failed for the DASD\n");
2745 	erp_fn = device->discipline->erp_postaction(cqr);
2746 	erp_fn(cqr);
2747 }
2748 
2749 static void __dasd_cleanup_cqr(struct dasd_ccw_req *cqr)
2750 {
2751 	struct request *req;
2752 	blk_status_t error = BLK_STS_OK;
2753 	unsigned int proc_bytes;
2754 	int status, intrc;
2755 
2756 	req = (struct request *) cqr->callback_data;
2757 	dasd_profile_end(cqr->block, cqr, req);
2758 
2759 	/*
2760 	 * free_cp() returns the request block to its memory pool, so snapshot
2761 	 * everything still needed from cqr before calling it - another CPU can
2762 	 * reallocate and overwrite the block right after.
2763 	 */
2764 	proc_bytes = cqr->proc_bytes;
2765 	intrc = cqr->intrc;
2766 	status = cqr->block->base->discipline->free_cp(cqr, req);
2767 	if (status < 0)
2768 		error = errno_to_blk_status(status);
2769 	else if (status == 0) {
2770 		switch (intrc) {
2771 		case -EPERM:
2772 			/*
2773 			 * DASD doesn't implement SCSI/NVMe reservations, but it
2774 			 * implements a locking scheme similar to them. We
2775 			 * return this error when we no longer have the lock.
2776 			 */
2777 			error = BLK_STS_RESV_CONFLICT;
2778 			break;
2779 		case -ENOLINK:
2780 			error = BLK_STS_TRANSPORT;
2781 			break;
2782 		case -ETIMEDOUT:
2783 			error = BLK_STS_TIMEOUT;
2784 			break;
2785 		default:
2786 			error = BLK_STS_IOERR;
2787 			break;
2788 		}
2789 	} else if (status == DASD_CQR_ABORTED) {
2790 		/* aborted requests are replaced with a new one so do not complete this */
2791 		return;
2792 	}
2793 
2794 	/*
2795 	 * We need to take care for ETIMEDOUT errors here since the
2796 	 * complete callback does not get called in this case.
2797 	 * Take care of all errors here and avoid additional code to
2798 	 * transfer the error value to the complete callback.
2799 	 */
2800 	if (error) {
2801 		blk_mq_end_request(req, error);
2802 		blk_mq_run_hw_queues(req->q, true);
2803 	} else {
2804 		/*
2805 		 * Partial completed requests can happen with ESE devices.
2806 		 * During read we might have gotten a NRF error and have to
2807 		 * complete a request partially.
2808 		 */
2809 		if (proc_bytes) {
2810 			blk_update_request(req, BLK_STS_OK, proc_bytes);
2811 			blk_mq_requeue_request(req, true);
2812 		} else if (likely(!blk_should_fake_timeout(req->q))) {
2813 			blk_mq_complete_request(req);
2814 		}
2815 	}
2816 }
2817 
2818 /*
2819  * Process ccw request queue.
2820  */
2821 static void __dasd_process_block_ccw_queue(struct dasd_block *block,
2822 					   struct list_head *final_queue)
2823 {
2824 	struct list_head *l, *n;
2825 	struct dasd_ccw_req *cqr;
2826 	dasd_erp_fn_t erp_fn;
2827 	unsigned long flags;
2828 	struct dasd_device *base = block->base;
2829 
2830 restart:
2831 	/* Process request with final status. */
2832 	list_for_each_safe(l, n, &block->ccw_queue) {
2833 		cqr = list_entry(l, struct dasd_ccw_req, blocklist);
2834 		if (cqr->status != DASD_CQR_DONE &&
2835 		    cqr->status != DASD_CQR_FAILED &&
2836 		    cqr->status != DASD_CQR_NEED_ERP &&
2837 		    cqr->status != DASD_CQR_TERMINATED &&
2838 		    cqr->status != DASD_CQR_ABORTED)
2839 			continue;
2840 
2841 		if (cqr->status == DASD_CQR_TERMINATED) {
2842 			base->discipline->handle_terminated_request(cqr);
2843 			goto restart;
2844 		}
2845 
2846 		/*  Process requests that may be recovered */
2847 		if (cqr->status == DASD_CQR_NEED_ERP) {
2848 			erp_fn = base->discipline->erp_action(cqr);
2849 			if (IS_ERR(erp_fn(cqr)))
2850 				continue;
2851 			goto restart;
2852 		}
2853 
2854 		/* log sense for fatal error */
2855 		if (cqr->status == DASD_CQR_FAILED) {
2856 			dasd_log_sense(cqr, &cqr->irb);
2857 		}
2858 
2859 		/*
2860 		 * First call extended error reporting and check for autoquiesce
2861 		 */
2862 		spin_lock_irqsave(get_ccwdev_lock(base->cdev), flags);
2863 		if (cqr->status == DASD_CQR_FAILED &&
2864 		    dasd_handle_autoquiesce(base, cqr, DASD_EER_FATALERROR)) {
2865 			cqr->status = DASD_CQR_FILLED;
2866 			cqr->retries = 255;
2867 			spin_unlock_irqrestore(get_ccwdev_lock(base->cdev), flags);
2868 			goto restart;
2869 		}
2870 		spin_unlock_irqrestore(get_ccwdev_lock(base->cdev), flags);
2871 
2872 		/* Process finished ERP request. */
2873 		if (cqr->refers) {
2874 			__dasd_process_erp(base, cqr);
2875 			goto restart;
2876 		}
2877 
2878 		/* Rechain finished requests to final queue */
2879 		cqr->endclk = get_tod_clock();
2880 		list_move_tail(&cqr->blocklist, final_queue);
2881 	}
2882 }
2883 
2884 static void dasd_return_cqr_cb(struct dasd_ccw_req *cqr, void *data)
2885 {
2886 	struct dasd_ccw_req *temp_cqr;
2887 	struct dasd_block *block;
2888 
2889 	/* only format CQRs are candidates */
2890 	if (!cqr->block || unlikely(!cqr->format))
2891 		goto out;
2892 
2893 	block = cqr->block;
2894 	/*
2895 	 * Mark in-flight (IN_IO) CQRs that overlap this just-completed format
2896 	 * range so they re-check in test_and_set_format on completion; FILLED
2897 	 * or QUEUED CQRs re-check the format_list on their next round anyway.
2898 	 */
2899 	list_for_each_entry(temp_cqr, &block->ccw_queue, blocklist) {
2900 		if (temp_cqr != cqr &&
2901 		    temp_cqr->status != DASD_CQR_FILLED &&
2902 		    temp_cqr->status != DASD_CQR_QUEUED &&
2903 		    dasd_req_conflict(cqr, temp_cqr)) {
2904 			WRITE_ONCE(temp_cqr->collision, true);
2905 		}
2906 	}
2907 out:
2908 	dasd_schedule_block_bh(cqr->block);
2909 }
2910 
2911 static void __dasd_block_start_head(struct dasd_block *block)
2912 {
2913 	struct dasd_ccw_req *cqr;
2914 
2915 	if (list_empty(&block->ccw_queue))
2916 		return;
2917 	/* We allways begin with the first requests on the queue, as some
2918 	 * of previously started requests have to be enqueued on a
2919 	 * dasd_device again for error recovery.
2920 	 */
2921 	list_for_each_entry(cqr, &block->ccw_queue, blocklist) {
2922 		if (cqr->status != DASD_CQR_FILLED)
2923 			continue;
2924 		if (test_bit(DASD_FLAG_LOCK_STOLEN, &block->base->flags) &&
2925 		    !test_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags)) {
2926 			cqr->status = DASD_CQR_FAILED;
2927 			cqr->intrc = -EPERM;
2928 			dasd_schedule_block_bh(block);
2929 			continue;
2930 		}
2931 		/* Non-temporary stop condition will trigger fail fast */
2932 		if (block->base->stopped & ~DASD_STOPPED_PENDING &&
2933 		    test_bit(DASD_CQR_FLAGS_FAILFAST, &cqr->flags) &&
2934 		    !dasd_eer_enabled(block->base) && block->base->aq_mask == 0) {
2935 			cqr->status = DASD_CQR_FAILED;
2936 			cqr->intrc = -ENOLINK;
2937 			dasd_schedule_block_bh(block);
2938 			continue;
2939 		}
2940 		/* Don't try to start requests if device is stopped */
2941 		if (block->base->stopped)
2942 			return;
2943 
2944 		/* just a fail safe check, should not happen */
2945 		if (!cqr->startdev)
2946 			cqr->startdev = block->base;
2947 
2948 		/* make sure that the requests we submit find their way back */
2949 		cqr->callback = dasd_return_cqr_cb;
2950 
2951 		dasd_add_request_tail(cqr);
2952 	}
2953 }
2954 
2955 /*
2956  * Central dasd_block layer routine. Takes requests from the generic
2957  * block layer request queue, creates ccw requests, enqueues them on
2958  * a dasd_device and processes ccw requests that have been returned.
2959  */
2960 static void dasd_block_tasklet(unsigned long data)
2961 {
2962 	struct dasd_block *block = (struct dasd_block *) data;
2963 	struct list_head final_queue;
2964 	struct list_head *l, *n;
2965 	struct dasd_ccw_req *cqr;
2966 	struct dasd_queue *dq;
2967 
2968 	atomic_set(&block->tasklet_scheduled, 0);
2969 	INIT_LIST_HEAD(&final_queue);
2970 	spin_lock_irq(&block->queue_lock);
2971 	/*
2972 	 * Splice the hardirq-staged ESE format CQRs onto ccw_queue. Splice to
2973 	 * the tail so an aborted origin request (already on ccw_queue) is
2974 	 * retired before its format-CQR replacement completes and requeues it.
2975 	 */
2976 	spin_lock(&block->ese_lock);
2977 	list_splice_tail_init(&block->ese_staging, &block->ccw_queue);
2978 	spin_unlock(&block->ese_lock);
2979 	/* Finish off requests on ccw queue */
2980 	__dasd_process_block_ccw_queue(block, &final_queue);
2981 	spin_unlock_irq(&block->queue_lock);
2982 
2983 	/* Now call the callback function of requests with final status */
2984 	list_for_each_safe(l, n, &final_queue) {
2985 		cqr = list_entry(l, struct dasd_ccw_req, blocklist);
2986 		dq = cqr->dq;
2987 		spin_lock_irq(&dq->lock);
2988 		list_del_init(&cqr->blocklist);
2989 		__dasd_cleanup_cqr(cqr);
2990 		spin_unlock_irq(&dq->lock);
2991 	}
2992 
2993 	spin_lock_irq(&block->queue_lock);
2994 	/* Now check if the head of the ccw queue needs to be started. */
2995 	__dasd_block_start_head(block);
2996 	spin_unlock_irq(&block->queue_lock);
2997 
2998 	if (waitqueue_active(&shutdown_waitq))
2999 		wake_up(&shutdown_waitq);
3000 	dasd_put_device(block->base);
3001 }
3002 
3003 static void _dasd_wake_block_flush_cb(struct dasd_ccw_req *cqr, void *data)
3004 {
3005 	wake_up(&dasd_flush_wq);
3006 }
3007 
3008 /*
3009  * Requeue a request back to the block request queue
3010  * only works for block requests
3011  */
3012 static void _dasd_requeue_request(struct dasd_ccw_req *cqr)
3013 {
3014 	struct request *req;
3015 
3016 	/*
3017 	 * If the request is an ERP request there is nothing to requeue.
3018 	 * This will be done with the remaining original request.
3019 	 */
3020 	if (cqr->refers)
3021 		return;
3022 	spin_lock_irq(&cqr->dq->lock);
3023 	req = (struct request *) cqr->callback_data;
3024 	blk_mq_requeue_request(req, true);
3025 	spin_unlock_irq(&cqr->dq->lock);
3026 
3027 	return;
3028 }
3029 
3030 static int _dasd_requests_to_flushqueue(struct dasd_block *block,
3031 					struct list_head *flush_queue)
3032 {
3033 	struct dasd_ccw_req *cqr, *n;
3034 	unsigned long flags;
3035 	int rc, i;
3036 
3037 	spin_lock_irqsave(&block->queue_lock, flags);
3038 	/*
3039 	 * Splice any hardirq-staged ESE format CQRs onto ccw_queue first so
3040 	 * they are seen and canceled by the walk below instead of being
3041 	 * orphaned across this flush / state transition. Mirrors the splice
3042 	 * in dasd_block_tasklet().
3043 	 */
3044 	spin_lock(&block->ese_lock);
3045 	list_splice_tail_init(&block->ese_staging, &block->ccw_queue);
3046 	spin_unlock(&block->ese_lock);
3047 	rc = 0;
3048 restart:
3049 	list_for_each_entry_safe(cqr, n, &block->ccw_queue, blocklist) {
3050 		/* if this request currently owned by a dasd_device cancel it */
3051 		if (cqr->status >= DASD_CQR_QUEUED)
3052 			rc = dasd_cancel_req(cqr);
3053 		if (rc < 0)
3054 			break;
3055 		/* Rechain request (including erp chain) so it won't be
3056 		 * touched by the dasd_block_tasklet anymore.
3057 		 * Replace the callback so we notice when the request
3058 		 * is returned from the dasd_device layer.
3059 		 */
3060 		cqr->callback = _dasd_wake_block_flush_cb;
3061 		for (i = 0; cqr; cqr = cqr->refers, i++)
3062 			list_move_tail(&cqr->blocklist, flush_queue);
3063 		if (i > 1)
3064 			/* moved more than one request - need to restart */
3065 			goto restart;
3066 	}
3067 	spin_unlock_irqrestore(&block->queue_lock, flags);
3068 
3069 	return rc;
3070 }
3071 
3072 /*
3073  * Go through all request on the dasd_block request queue, cancel them
3074  * on the respective dasd_device, and return them to the generic
3075  * block layer.
3076  */
3077 static int dasd_flush_block_queue(struct dasd_block *block)
3078 {
3079 	struct dasd_ccw_req *cqr, *n;
3080 	struct list_head flush_queue;
3081 	unsigned long flags;
3082 	int rc;
3083 
3084 	INIT_LIST_HEAD(&flush_queue);
3085 	rc = _dasd_requests_to_flushqueue(block, &flush_queue);
3086 
3087 	/* Now call the callback function of flushed requests */
3088 restart_cb:
3089 	list_for_each_entry_safe(cqr, n, &flush_queue, blocklist) {
3090 		wait_event(dasd_flush_wq, (cqr->status < DASD_CQR_QUEUED));
3091 		/* Process finished ERP request. */
3092 		if (cqr->refers) {
3093 			spin_lock_bh(&block->queue_lock);
3094 			__dasd_process_erp(block->base, cqr);
3095 			spin_unlock_bh(&block->queue_lock);
3096 			/* restart list_for_xx loop since dasd_process_erp
3097 			 * might remove multiple elements */
3098 			goto restart_cb;
3099 		}
3100 		/* call the callback function */
3101 		spin_lock_irqsave(&cqr->dq->lock, flags);
3102 		cqr->endclk = get_tod_clock();
3103 		list_del_init(&cqr->blocklist);
3104 		__dasd_cleanup_cqr(cqr);
3105 		spin_unlock_irqrestore(&cqr->dq->lock, flags);
3106 	}
3107 	return rc;
3108 }
3109 
3110 /*
3111  * Schedules a call to dasd_tasklet over the device tasklet.
3112  */
3113 void dasd_schedule_block_bh(struct dasd_block *block)
3114 {
3115 	/* Protect against rescheduling. */
3116 	if (atomic_cmpxchg(&block->tasklet_scheduled, 0, 1) != 0)
3117 		return;
3118 	/* life cycle of block is bound to it's base device */
3119 	dasd_get_device(block->base);
3120 	tasklet_hi_schedule(&block->tasklet);
3121 }
3122 EXPORT_SYMBOL(dasd_schedule_block_bh);
3123 
3124 
3125 /*
3126  * SECTION: external block device operations
3127  * (request queue handling, open, release, etc.)
3128  */
3129 
3130 /*
3131  * Dasd request queue function. Called from ll_rw_blk.c
3132  */
3133 static blk_status_t do_dasd_request(struct blk_mq_hw_ctx *hctx,
3134 				    const struct blk_mq_queue_data *qd)
3135 {
3136 	struct dasd_block *block = hctx->queue->queuedata;
3137 	struct dasd_queue *dq = hctx->driver_data;
3138 	struct request *req = qd->rq;
3139 	struct dasd_device *basedev;
3140 	struct dasd_ccw_req *cqr;
3141 	blk_status_t rc = BLK_STS_OK;
3142 	bool complete_noop = false;
3143 
3144 	basedev = block->base;
3145 	spin_lock_irq(&dq->lock);
3146 	if (basedev->state < DASD_STATE_READY ||
3147 	    test_bit(DASD_FLAG_OFFLINE, &basedev->flags)) {
3148 		DBF_DEV_EVENT(DBF_ERR, basedev,
3149 			      "device not ready for request %p", req);
3150 		rc = BLK_STS_IOERR;
3151 		goto out;
3152 	}
3153 
3154 	/*
3155 	 * if device is stopped do not fetch new requests
3156 	 * except failfast is active which will let requests fail
3157 	 * immediately in __dasd_block_start_head()
3158 	 */
3159 	if (basedev->stopped && !(basedev->features & DASD_FEATURE_FAILFAST)) {
3160 		DBF_DEV_EVENT(DBF_ERR, basedev,
3161 			      "device stopped request %p", req);
3162 		rc = BLK_STS_RESOURCE;
3163 		goto out;
3164 	}
3165 
3166 	if (basedev->features & DASD_FEATURE_READONLY &&
3167 	    rq_data_dir(req) == WRITE) {
3168 		DBF_DEV_EVENT(DBF_ERR, basedev,
3169 			      "Rejecting write request %p", req);
3170 		rc = BLK_STS_IOERR;
3171 		goto out;
3172 	}
3173 
3174 	if (test_bit(DASD_FLAG_ABORTALL, &basedev->flags) &&
3175 	    (basedev->features & DASD_FEATURE_FAILFAST ||
3176 	     blk_noretry_request(req))) {
3177 		DBF_DEV_EVENT(DBF_ERR, basedev,
3178 			      "Rejecting failfast request %p", req);
3179 		rc = BLK_STS_IOERR;
3180 		goto out;
3181 	}
3182 
3183 	cqr = basedev->discipline->build_cp(basedev, block, req);
3184 	if (IS_ERR(cqr)) {
3185 		if (PTR_ERR(cqr) == -EBUSY ||
3186 		    PTR_ERR(cqr) == -ENOMEM ||
3187 		    PTR_ERR(cqr) == -EAGAIN) {
3188 			rc = BLK_STS_RESOURCE;
3189 		} else if (PTR_ERR(cqr) == -EINVAL) {
3190 			rc = BLK_STS_INVAL;
3191 		} else if (PTR_ERR(cqr) == -EOPNOTSUPP) {
3192 			/*
3193 			 * A discard that covers no whole extent releases
3194 			 * nothing. Discard is advisory, so complete it as a
3195 			 * benign no-op: the device does support discard, this
3196 			 * range just does not align to the large ESE extent
3197 			 * granularity.
3198 			 * Completed after the lock is dropped.
3199 			 */
3200 			rc = BLK_STS_OK;
3201 			complete_noop = true;
3202 		} else {
3203 			DBF_DEV_EVENT(DBF_ERR, basedev,
3204 				      "CCW creation failed (rc=%ld) on request %p",
3205 				      PTR_ERR(cqr), req);
3206 			rc = BLK_STS_IOERR;
3207 		}
3208 		goto out;
3209 	}
3210 	if (!cqr) {
3211 		/* build_cp may collapse a non-transient build error to NULL */
3212 		DBF_DEV_EVENT(DBF_ERR, basedev,
3213 			      "CCW creation returned NULL on request %p", req);
3214 		rc = BLK_STS_IOERR;
3215 		goto out;
3216 	}
3217 	/*
3218 	 *  Note: callback is set to dasd_return_cqr_cb in
3219 	 * __dasd_block_start_head to cover erp requests as well
3220 	 */
3221 	cqr->callback_data = req;
3222 	cqr->status = DASD_CQR_FILLED;
3223 	cqr->dq = dq;
3224 
3225 	blk_mq_start_request(req);
3226 	spin_lock(&block->queue_lock);
3227 	list_add_tail(&cqr->blocklist, &block->ccw_queue);
3228 	INIT_LIST_HEAD(&cqr->devlist);
3229 	dasd_profile_start(block, cqr, req);
3230 	dasd_schedule_block_bh(block);
3231 	spin_unlock(&block->queue_lock);
3232 
3233 out:
3234 	spin_unlock_irq(&dq->lock);
3235 	if (complete_noop)
3236 		blk_mq_end_request(req, BLK_STS_OK);
3237 	return rc;
3238 }
3239 
3240 /*
3241  * Block timeout callback, called from the block layer
3242  *
3243  * Return values:
3244  * BLK_EH_RESET_TIMER if the request should be left running
3245  * BLK_EH_DONE if the request is handled or terminated
3246  *		      by the driver.
3247  */
3248 enum blk_eh_timer_return dasd_times_out(struct request *req)
3249 {
3250 	struct dasd_block *block = req->q->queuedata;
3251 	struct dasd_device *device;
3252 	struct dasd_ccw_req *cqr;
3253 	unsigned long flags;
3254 	int rc = 0;
3255 
3256 	cqr = blk_mq_rq_to_pdu(req);
3257 	if (!cqr)
3258 		return BLK_EH_DONE;
3259 
3260 	spin_lock_irqsave(&cqr->dq->lock, flags);
3261 	device = cqr->startdev ? cqr->startdev : block->base;
3262 	if (!device->blk_timeout) {
3263 		spin_unlock_irqrestore(&cqr->dq->lock, flags);
3264 		return BLK_EH_RESET_TIMER;
3265 	}
3266 	DBF_DEV_EVENT(DBF_WARNING, device,
3267 		      " dasd_times_out cqr %p status %x",
3268 		      cqr, cqr->status);
3269 
3270 	spin_lock(&block->queue_lock);
3271 	spin_lock(get_ccwdev_lock(device->cdev));
3272 	cqr->retries = -1;
3273 	cqr->intrc = -ETIMEDOUT;
3274 	if (cqr->status >= DASD_CQR_QUEUED) {
3275 		rc = __dasd_cancel_req(cqr);
3276 	} else if (cqr->status == DASD_CQR_FILLED ||
3277 		   cqr->status == DASD_CQR_NEED_ERP) {
3278 		cqr->status = DASD_CQR_TERMINATED;
3279 	} else if (cqr->status == DASD_CQR_IN_ERP) {
3280 		struct dasd_ccw_req *searchcqr, *nextcqr, *tmpcqr;
3281 
3282 		list_for_each_entry_safe(searchcqr, nextcqr,
3283 					 &block->ccw_queue, blocklist) {
3284 			tmpcqr = searchcqr;
3285 			while (tmpcqr->refers)
3286 				tmpcqr = tmpcqr->refers;
3287 			if (tmpcqr != cqr)
3288 				continue;
3289 			/* searchcqr is an ERP request for cqr */
3290 			searchcqr->retries = -1;
3291 			searchcqr->intrc = -ETIMEDOUT;
3292 			if (searchcqr->status >= DASD_CQR_QUEUED) {
3293 				rc = __dasd_cancel_req(searchcqr);
3294 			} else if ((searchcqr->status == DASD_CQR_FILLED) ||
3295 				   (searchcqr->status == DASD_CQR_NEED_ERP)) {
3296 				searchcqr->status = DASD_CQR_TERMINATED;
3297 				rc = 0;
3298 			} else if (searchcqr->status == DASD_CQR_IN_ERP) {
3299 				/*
3300 				 * Shouldn't happen; most recent ERP
3301 				 * request is at the front of queue
3302 				 */
3303 				continue;
3304 			}
3305 			break;
3306 		}
3307 	}
3308 	spin_unlock(get_ccwdev_lock(device->cdev));
3309 	dasd_schedule_block_bh(block);
3310 	spin_unlock(&block->queue_lock);
3311 	spin_unlock_irqrestore(&cqr->dq->lock, flags);
3312 
3313 	return rc ? BLK_EH_RESET_TIMER : BLK_EH_DONE;
3314 }
3315 
3316 static int dasd_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
3317 			  unsigned int idx)
3318 {
3319 	struct dasd_queue *dq = kzalloc_obj(*dq);
3320 
3321 	if (!dq)
3322 		return -ENOMEM;
3323 
3324 	spin_lock_init(&dq->lock);
3325 	hctx->driver_data = dq;
3326 
3327 	return 0;
3328 }
3329 
3330 static void dasd_exit_hctx(struct blk_mq_hw_ctx *hctx, unsigned int idx)
3331 {
3332 	kfree(hctx->driver_data);
3333 	hctx->driver_data = NULL;
3334 }
3335 
3336 static void dasd_request_done(struct request *req)
3337 {
3338 	blk_mq_end_request(req, 0);
3339 	blk_mq_run_hw_queues(req->q, true);
3340 }
3341 
3342 struct blk_mq_ops dasd_mq_ops = {
3343 	.queue_rq = do_dasd_request,
3344 	.complete = dasd_request_done,
3345 	.timeout = dasd_times_out,
3346 	.init_hctx = dasd_init_hctx,
3347 	.exit_hctx = dasd_exit_hctx,
3348 };
3349 
3350 static int dasd_open(struct gendisk *disk, blk_mode_t mode)
3351 {
3352 	struct dasd_device *base;
3353 	int rc;
3354 
3355 	base = dasd_device_from_gendisk(disk);
3356 	if (!base)
3357 		return -ENODEV;
3358 
3359 	atomic_inc(&base->block->open_count);
3360 	if (test_bit(DASD_FLAG_OFFLINE, &base->flags)) {
3361 		rc = -ENODEV;
3362 		goto unlock;
3363 	}
3364 
3365 	if (!try_module_get(base->discipline->owner)) {
3366 		rc = -EINVAL;
3367 		goto unlock;
3368 	}
3369 
3370 	if (dasd_probeonly) {
3371 		dev_info(&base->cdev->dev,
3372 			 "Accessing the DASD failed because it is in "
3373 			 "probeonly mode\n");
3374 		rc = -EPERM;
3375 		goto out;
3376 	}
3377 
3378 	if (base->state <= DASD_STATE_BASIC) {
3379 		DBF_DEV_EVENT(DBF_ERR, base, " %s",
3380 			      " Cannot open unrecognized device");
3381 		rc = -ENODEV;
3382 		goto out;
3383 	}
3384 	if ((mode & BLK_OPEN_WRITE) &&
3385 	    (test_bit(DASD_FLAG_DEVICE_RO, &base->flags) ||
3386 	     (base->features & DASD_FEATURE_READONLY))) {
3387 		rc = -EROFS;
3388 		goto out;
3389 	}
3390 	dasd_put_device(base);
3391 	return 0;
3392 
3393 out:
3394 	module_put(base->discipline->owner);
3395 unlock:
3396 	atomic_dec(&base->block->open_count);
3397 	dasd_put_device(base);
3398 	return rc;
3399 }
3400 
3401 static void dasd_release(struct gendisk *disk)
3402 {
3403 	struct dasd_device *base = dasd_device_from_gendisk(disk);
3404 	if (base) {
3405 		atomic_dec(&base->block->open_count);
3406 		module_put(base->discipline->owner);
3407 		dasd_put_device(base);
3408 	}
3409 }
3410 
3411 /*
3412  * Return disk geometry.
3413  */
3414 static int dasd_getgeo(struct gendisk *disk, struct hd_geometry *geo)
3415 {
3416 	struct dasd_device *base;
3417 
3418 	base = dasd_device_from_gendisk(disk);
3419 	if (!base)
3420 		return -ENODEV;
3421 
3422 	if (!base->discipline ||
3423 	    !base->discipline->fill_geometry) {
3424 		dasd_put_device(base);
3425 		return -EINVAL;
3426 	}
3427 	base->discipline->fill_geometry(base->block, geo);
3428 	// geo->start is left unchanged by the above
3429 	geo->start >>= base->block->s2b_shift;
3430 	dasd_put_device(base);
3431 	return 0;
3432 }
3433 
3434 const struct block_device_operations
3435 dasd_device_operations = {
3436 	.owner		= THIS_MODULE,
3437 	.open		= dasd_open,
3438 	.release	= dasd_release,
3439 	.ioctl		= dasd_ioctl,
3440 	.getgeo		= dasd_getgeo,
3441 	.set_read_only	= dasd_set_read_only,
3442 };
3443 
3444 /*******************************************************************************
3445  * end of block device operations
3446  */
3447 
3448 static void
3449 dasd_exit(void)
3450 {
3451 #ifdef CONFIG_PROC_FS
3452 	dasd_proc_exit();
3453 #endif
3454 	dasd_eer_exit();
3455 	kmem_cache_destroy(dasd_page_cache);
3456 	dasd_page_cache = NULL;
3457 	dasd_gendisk_exit();
3458 	dasd_devmap_exit();
3459 	if (dasd_debug_area != NULL) {
3460 		debug_unregister(dasd_debug_area);
3461 		dasd_debug_area = NULL;
3462 	}
3463 	dasd_statistics_removeroot();
3464 }
3465 
3466 /*
3467  * SECTION: common functions for ccw_driver use
3468  */
3469 
3470 /*
3471  * Is the device read-only?
3472  * Note that this function does not report the setting of the
3473  * readonly device attribute, but how it is configured in z/VM.
3474  */
3475 int dasd_device_is_ro(struct dasd_device *device)
3476 {
3477 	struct ccw_dev_id dev_id;
3478 	struct diag210 diag_data;
3479 	int rc;
3480 
3481 	if (!machine_is_vm())
3482 		return 0;
3483 	ccw_device_get_id(device->cdev, &dev_id);
3484 	memset(&diag_data, 0, sizeof(diag_data));
3485 	diag_data.vrdcdvno = dev_id.devno;
3486 	diag_data.vrdclen = sizeof(diag_data);
3487 	rc = diag210(&diag_data);
3488 	if (rc == 0 || rc == 2) {
3489 		return diag_data.vrdcvfla & 0x80;
3490 	} else {
3491 		DBF_EVENT(DBF_WARNING, "diag210 failed for dev=%04x with rc=%d",
3492 			  dev_id.devno, rc);
3493 		return 0;
3494 	}
3495 }
3496 EXPORT_SYMBOL_GPL(dasd_device_is_ro);
3497 
3498 static void dasd_generic_auto_online(void *data, async_cookie_t cookie)
3499 {
3500 	struct ccw_device *cdev = data;
3501 	int ret;
3502 
3503 	ret = ccw_device_set_online(cdev);
3504 	if (ret)
3505 		dev_warn(&cdev->dev, "Setting the DASD online failed with rc=%d\n", ret);
3506 }
3507 
3508 /*
3509  * Initial attempt at a probe function. this can be simplified once
3510  * the other detection code is gone.
3511  */
3512 int dasd_generic_probe(struct ccw_device *cdev)
3513 {
3514 	cdev->handler = &dasd_int_handler;
3515 
3516 	/*
3517 	 * Automatically online either all dasd devices (dasd_autodetect)
3518 	 * or all devices specified with dasd= parameters during
3519 	 * initial probe.
3520 	 */
3521 	if ((dasd_get_feature(cdev, DASD_FEATURE_INITIAL_ONLINE) > 0 ) ||
3522 	    (dasd_autodetect && dasd_busid_known(dev_name(&cdev->dev)) != 0))
3523 		async_schedule(dasd_generic_auto_online, cdev);
3524 	return 0;
3525 }
3526 EXPORT_SYMBOL_GPL(dasd_generic_probe);
3527 
3528 void dasd_generic_free_discipline(struct dasd_device *device)
3529 {
3530 	/* Forget the discipline information. */
3531 	if (device->discipline) {
3532 		if (device->discipline->uncheck_device)
3533 			device->discipline->uncheck_device(device);
3534 		module_put(device->discipline->owner);
3535 		device->discipline = NULL;
3536 	}
3537 	if (device->base_discipline) {
3538 		module_put(device->base_discipline->owner);
3539 		device->base_discipline = NULL;
3540 	}
3541 }
3542 EXPORT_SYMBOL_GPL(dasd_generic_free_discipline);
3543 
3544 /*
3545  * This will one day be called from a global not_oper handler.
3546  * It is also used by driver_unregister during module unload.
3547  */
3548 void dasd_generic_remove(struct ccw_device *cdev)
3549 {
3550 	struct dasd_device *device;
3551 	struct dasd_block *block;
3552 
3553 	device = dasd_device_from_cdev(cdev);
3554 	if (IS_ERR(device))
3555 		return;
3556 
3557 	if (test_and_set_bit(DASD_FLAG_OFFLINE, &device->flags) &&
3558 	    !test_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
3559 		/* Already doing offline processing */
3560 		dasd_put_device(device);
3561 		return;
3562 	}
3563 	/*
3564 	 * This device is removed unconditionally. Set offline
3565 	 * flag to prevent dasd_open from opening it while it is
3566 	 * no quite down yet.
3567 	 */
3568 	dasd_set_target_state(device, DASD_STATE_NEW);
3569 	cdev->handler = NULL;
3570 	/* dasd_delete_device destroys the device reference. */
3571 	block = device->block;
3572 	dasd_delete_device(device);
3573 	/*
3574 	 * life cycle of block is bound to device, so delete it after
3575 	 * device was safely removed
3576 	 */
3577 	if (block)
3578 		dasd_free_block(block);
3579 }
3580 EXPORT_SYMBOL_GPL(dasd_generic_remove);
3581 
3582 /*
3583  * Activate a device. This is called from dasd_{eckd,fba}_probe() when either
3584  * the device is detected for the first time and is supposed to be used
3585  * or the user has started activation through sysfs.
3586  */
3587 int dasd_generic_set_online(struct ccw_device *cdev,
3588 			    struct dasd_discipline *base_discipline)
3589 {
3590 	struct dasd_discipline *discipline;
3591 	struct dasd_device *device;
3592 	struct device *dev;
3593 	int rc;
3594 
3595 	dev = &cdev->dev;
3596 
3597 	/* first online clears initial online feature flag */
3598 	dasd_set_feature(cdev, DASD_FEATURE_INITIAL_ONLINE, 0);
3599 	device = dasd_create_device(cdev);
3600 	if (IS_ERR(device))
3601 		return PTR_ERR(device);
3602 
3603 	discipline = base_discipline;
3604 	if (device->features & DASD_FEATURE_USEDIAG) {
3605 	  	if (!dasd_diag_discipline_pointer) {
3606 			/* Try to load the required module. */
3607 			rc = request_module(DASD_DIAG_MOD);
3608 			if (rc) {
3609 				dev_warn(dev, "Setting the DASD online failed "
3610 					 "because the required module %s "
3611 					 "could not be loaded (rc=%d)\n",
3612 					 DASD_DIAG_MOD, rc);
3613 				dasd_delete_device(device);
3614 				return -ENODEV;
3615 			}
3616 		}
3617 		/* Module init could have failed, so check again here after
3618 		 * request_module(). */
3619 		if (!dasd_diag_discipline_pointer) {
3620 			dev_warn(dev, "Setting the DASD online failed because of missing DIAG discipline\n");
3621 			dasd_delete_device(device);
3622 			return -ENODEV;
3623 		}
3624 		discipline = dasd_diag_discipline_pointer;
3625 	}
3626 	if (!try_module_get(base_discipline->owner)) {
3627 		dasd_delete_device(device);
3628 		return -EINVAL;
3629 	}
3630 	device->base_discipline = base_discipline;
3631 	if (!try_module_get(discipline->owner)) {
3632 		dasd_delete_device(device);
3633 		return -EINVAL;
3634 	}
3635 	device->discipline = discipline;
3636 
3637 	/* check_device will allocate block device if necessary */
3638 	rc = discipline->check_device(device);
3639 	if (rc) {
3640 		dev_warn(dev, "Setting the DASD online with discipline %s failed with rc=%i\n",
3641 			 discipline->name, rc);
3642 		dasd_delete_device(device);
3643 		return rc;
3644 	}
3645 
3646 	dasd_set_target_state(device, DASD_STATE_ONLINE);
3647 	if (device->state <= DASD_STATE_KNOWN) {
3648 		dev_warn(dev, "Setting the DASD online failed because of a missing discipline\n");
3649 		rc = -ENODEV;
3650 		dasd_set_target_state(device, DASD_STATE_NEW);
3651 		if (device->block)
3652 			dasd_free_block(device->block);
3653 		dasd_delete_device(device);
3654 	} else {
3655 		dev_dbg(dev, "dasd_generic device found\n");
3656 	}
3657 
3658 	wait_event(dasd_init_waitq, _wait_for_device(device));
3659 
3660 	dasd_put_device(device);
3661 	return rc;
3662 }
3663 EXPORT_SYMBOL_GPL(dasd_generic_set_online);
3664 
3665 int dasd_generic_set_offline(struct ccw_device *cdev)
3666 {
3667 	int max_count, open_count, rc;
3668 	struct dasd_device *device;
3669 	struct dasd_block *block;
3670 	unsigned long flags;
3671 	struct device *dev;
3672 
3673 	dev = &cdev->dev;
3674 
3675 	rc = 0;
3676 	spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
3677 	device = dasd_device_from_cdev_locked(cdev);
3678 	if (IS_ERR(device)) {
3679 		spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
3680 		return PTR_ERR(device);
3681 	}
3682 
3683 	/*
3684 	 * We must make sure that this device is currently not in use.
3685 	 * The open_count is increased for every opener, that includes
3686 	 * the blkdev_get in dasd_scan_partitions. We are only interested
3687 	 * in the other openers.
3688 	 */
3689 	if (device->block) {
3690 		max_count = device->block->bdev_file ? 0 : -1;
3691 		open_count = atomic_read(&device->block->open_count);
3692 		if (open_count > max_count) {
3693 			if (open_count > 0)
3694 				dev_warn(dev, "The DASD cannot be set offline with open count %i\n",
3695 					 open_count);
3696 			else
3697 				dev_warn(dev, "The DASD cannot be set offline while it is in use\n");
3698 			rc = -EBUSY;
3699 			goto out_err;
3700 		}
3701 	}
3702 
3703 	/*
3704 	 * Test if the offline processing is already running and exit if so.
3705 	 * If a safe offline is being processed this could only be a normal
3706 	 * offline that should be able to overtake the safe offline and
3707 	 * cancel any I/O we do not want to wait for any longer
3708 	 */
3709 	if (test_bit(DASD_FLAG_OFFLINE, &device->flags)) {
3710 		if (test_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
3711 			clear_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING,
3712 				  &device->flags);
3713 		} else {
3714 			rc = -EBUSY;
3715 			goto out_err;
3716 		}
3717 	}
3718 	set_bit(DASD_FLAG_OFFLINE, &device->flags);
3719 
3720 	/*
3721 	 * if safe_offline is called set safe_offline_running flag and
3722 	 * clear safe_offline so that a call to normal offline
3723 	 * can overrun safe_offline processing
3724 	 */
3725 	if (test_and_clear_bit(DASD_FLAG_SAFE_OFFLINE, &device->flags) &&
3726 	    !test_and_set_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
3727 		/* need to unlock here to wait for outstanding I/O */
3728 		spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
3729 		/*
3730 		 * If we want to set the device safe offline all IO operations
3731 		 * should be finished before continuing the offline process
3732 		 * so sync bdev first and then wait for our queues to become
3733 		 * empty
3734 		 */
3735 		if (device->block && device->block->bdev_file)
3736 			bdev_mark_dead(file_bdev(device->block->bdev_file), false);
3737 		dasd_schedule_device_bh(device);
3738 		rc = wait_event_interruptible(shutdown_waitq,
3739 					      _wait_for_empty_queues(device));
3740 		if (rc != 0)
3741 			goto interrupted;
3742 
3743 		/*
3744 		 * check if a normal offline process overtook the offline
3745 		 * processing in this case simply do nothing beside returning
3746 		 * that we got interrupted
3747 		 * otherwise mark safe offline as not running any longer and
3748 		 * continue with normal offline
3749 		 */
3750 		spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
3751 		if (!test_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags)) {
3752 			rc = -ERESTARTSYS;
3753 			goto out_err;
3754 		}
3755 		clear_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags);
3756 	}
3757 	spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
3758 
3759 	dasd_set_target_state(device, DASD_STATE_NEW);
3760 	/* dasd_delete_device destroys the device reference. */
3761 	block = device->block;
3762 	dasd_delete_device(device);
3763 	/*
3764 	 * life cycle of block is bound to device, so delete it after
3765 	 * device was safely removed
3766 	 */
3767 	if (block)
3768 		dasd_free_block(block);
3769 
3770 	return 0;
3771 
3772 interrupted:
3773 	/* interrupted by signal */
3774 	spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
3775 	clear_bit(DASD_FLAG_SAFE_OFFLINE_RUNNING, &device->flags);
3776 	clear_bit(DASD_FLAG_OFFLINE, &device->flags);
3777 out_err:
3778 	dasd_put_device(device);
3779 	spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
3780 	return rc;
3781 }
3782 EXPORT_SYMBOL_GPL(dasd_generic_set_offline);
3783 
3784 int dasd_generic_last_path_gone(struct dasd_device *device)
3785 {
3786 	struct dasd_ccw_req *cqr;
3787 
3788 	dev_warn(&device->cdev->dev, "No operational channel path is left "
3789 		 "for the device\n");
3790 	DBF_DEV_EVENT(DBF_WARNING, device, "%s", "last path gone");
3791 	/* First call extended error reporting and check for autoquiesce. */
3792 	dasd_handle_autoquiesce(device, NULL, DASD_EER_NOPATH);
3793 
3794 	if (device->state < DASD_STATE_BASIC)
3795 		return 0;
3796 	/* Device is active. We want to keep it. */
3797 	list_for_each_entry(cqr, &device->ccw_queue, devlist)
3798 		if ((cqr->status == DASD_CQR_IN_IO) ||
3799 		    (cqr->status == DASD_CQR_CLEAR_PENDING)) {
3800 			cqr->status = DASD_CQR_QUEUED;
3801 			cqr->retries++;
3802 		}
3803 	dasd_device_set_stop_bits(device, DASD_STOPPED_DC_WAIT);
3804 	dasd_device_clear_timer(device);
3805 	dasd_schedule_device_bh(device);
3806 	return 1;
3807 }
3808 EXPORT_SYMBOL_GPL(dasd_generic_last_path_gone);
3809 
3810 int dasd_generic_path_operational(struct dasd_device *device)
3811 {
3812 	dev_info(&device->cdev->dev, "A channel path to the device has become "
3813 		 "operational\n");
3814 	DBF_DEV_EVENT(DBF_WARNING, device, "%s", "path operational");
3815 	dasd_device_remove_stop_bits(device, DASD_STOPPED_DC_WAIT);
3816 	dasd_schedule_device_bh(device);
3817 	if (device->block) {
3818 		dasd_schedule_block_bh(device->block);
3819 		if (device->block->gdp)
3820 			blk_mq_run_hw_queues(device->block->gdp->queue, true);
3821 	}
3822 
3823 	if (!device->stopped)
3824 		wake_up(&generic_waitq);
3825 
3826 	return 1;
3827 }
3828 EXPORT_SYMBOL_GPL(dasd_generic_path_operational);
3829 
3830 int dasd_generic_notify(struct ccw_device *cdev, int event)
3831 {
3832 	struct dasd_device *device;
3833 	int ret;
3834 
3835 	device = dasd_device_from_cdev_locked(cdev);
3836 	if (IS_ERR(device))
3837 		return 0;
3838 	ret = 0;
3839 	switch (event) {
3840 	case CIO_GONE:
3841 	case CIO_BOXED:
3842 	case CIO_NO_PATH:
3843 		dasd_path_no_path(device);
3844 		ret = dasd_generic_last_path_gone(device);
3845 		break;
3846 	case CIO_OPER:
3847 		ret = 1;
3848 		if (dasd_path_get_opm(device))
3849 			ret = dasd_generic_path_operational(device);
3850 		break;
3851 	}
3852 	dasd_put_device(device);
3853 	return ret;
3854 }
3855 EXPORT_SYMBOL_GPL(dasd_generic_notify);
3856 
3857 void dasd_generic_path_event(struct ccw_device *cdev, int *path_event)
3858 {
3859 	struct dasd_device *device;
3860 	int chp, oldopm, hpfpm, ifccpm;
3861 
3862 	device = dasd_device_from_cdev_locked(cdev);
3863 	if (IS_ERR(device))
3864 		return;
3865 
3866 	oldopm = dasd_path_get_opm(device);
3867 	for (chp = 0; chp < 8; chp++) {
3868 		if (path_event[chp] & PE_PATH_GONE) {
3869 			dasd_path_notoper(device, chp);
3870 		}
3871 		if (path_event[chp] & PE_PATH_AVAILABLE) {
3872 			dasd_path_available(device, chp);
3873 			dasd_schedule_device_bh(device);
3874 		}
3875 		if (path_event[chp] & PE_PATHGROUP_ESTABLISHED) {
3876 			if (!dasd_path_is_operational(device, chp) &&
3877 			    !dasd_path_need_verify(device, chp)) {
3878 				/*
3879 				 * we can not establish a pathgroup on an
3880 				 * unavailable path, so trigger a path
3881 				 * verification first
3882 				 */
3883 			dasd_path_available(device, chp);
3884 			dasd_schedule_device_bh(device);
3885 			}
3886 			DBF_DEV_EVENT(DBF_WARNING, device, "%s",
3887 				      "Pathgroup re-established\n");
3888 			if (device->discipline->kick_validate)
3889 				device->discipline->kick_validate(device);
3890 		}
3891 		if (path_event[chp] & PE_PATH_FCES_EVENT) {
3892 			dasd_path_fcsec_update(device, chp);
3893 			dasd_schedule_device_bh(device);
3894 		}
3895 	}
3896 	hpfpm = dasd_path_get_hpfpm(device);
3897 	ifccpm = dasd_path_get_ifccpm(device);
3898 	if (!dasd_path_get_opm(device) && hpfpm) {
3899 		/*
3900 		 * device has no operational paths but at least one path is
3901 		 * disabled due to HPF errors
3902 		 * disable HPF at all and use the path(s) again
3903 		 */
3904 		if (device->discipline->disable_hpf)
3905 			device->discipline->disable_hpf(device);
3906 		dasd_device_set_stop_bits(device, DASD_STOPPED_NOT_ACC);
3907 		dasd_path_set_tbvpm(device, hpfpm);
3908 		dasd_schedule_device_bh(device);
3909 		dasd_schedule_requeue(device);
3910 	} else if (!dasd_path_get_opm(device) && ifccpm) {
3911 		/*
3912 		 * device has no operational paths but at least one path is
3913 		 * disabled due to IFCC errors
3914 		 * trigger path verification on paths with IFCC errors
3915 		 */
3916 		dasd_path_set_tbvpm(device, ifccpm);
3917 		dasd_schedule_device_bh(device);
3918 	}
3919 	if (oldopm && !dasd_path_get_opm(device) && !hpfpm && !ifccpm) {
3920 		dev_warn(&device->cdev->dev,
3921 			 "No verified channel paths remain for the device\n");
3922 		DBF_DEV_EVENT(DBF_WARNING, device,
3923 			      "%s", "last verified path gone");
3924 		/* First call extended error reporting and check for autoquiesce. */
3925 		dasd_handle_autoquiesce(device, NULL, DASD_EER_NOPATH);
3926 		dasd_device_set_stop_bits(device,
3927 					  DASD_STOPPED_DC_WAIT);
3928 	}
3929 	dasd_put_device(device);
3930 }
3931 EXPORT_SYMBOL_GPL(dasd_generic_path_event);
3932 
3933 int dasd_generic_verify_path(struct dasd_device *device, __u8 lpm)
3934 {
3935 	if (!dasd_path_get_opm(device) && lpm) {
3936 		dasd_path_set_opm(device, lpm);
3937 		dasd_generic_path_operational(device);
3938 	} else
3939 		dasd_path_add_opm(device, lpm);
3940 	return 0;
3941 }
3942 EXPORT_SYMBOL_GPL(dasd_generic_verify_path);
3943 
3944 void dasd_generic_space_exhaust(struct dasd_device *device,
3945 				struct dasd_ccw_req *cqr)
3946 {
3947 	/* First call extended error reporting and check for autoquiesce. */
3948 	dasd_handle_autoquiesce(device, NULL, DASD_EER_NOSPC);
3949 
3950 	if (device->state < DASD_STATE_BASIC)
3951 		return;
3952 
3953 	if (cqr->status == DASD_CQR_IN_IO ||
3954 	    cqr->status == DASD_CQR_CLEAR_PENDING) {
3955 		cqr->status = DASD_CQR_QUEUED;
3956 		cqr->retries++;
3957 	}
3958 	dasd_device_set_stop_bits(device, DASD_STOPPED_NOSPC);
3959 	dasd_device_clear_timer(device);
3960 	dasd_schedule_device_bh(device);
3961 }
3962 EXPORT_SYMBOL_GPL(dasd_generic_space_exhaust);
3963 
3964 void dasd_generic_space_avail(struct dasd_device *device)
3965 {
3966 	dev_info(&device->cdev->dev, "Extent pool space is available\n");
3967 	DBF_DEV_EVENT(DBF_WARNING, device, "%s", "space available");
3968 
3969 	dasd_device_remove_stop_bits(device, DASD_STOPPED_NOSPC);
3970 	dasd_schedule_device_bh(device);
3971 
3972 	if (device->block) {
3973 		dasd_schedule_block_bh(device->block);
3974 		if (device->block->gdp)
3975 			blk_mq_run_hw_queues(device->block->gdp->queue, true);
3976 	}
3977 	if (!device->stopped)
3978 		wake_up(&generic_waitq);
3979 }
3980 EXPORT_SYMBOL_GPL(dasd_generic_space_avail);
3981 
3982 /*
3983  * clear active requests and requeue them to block layer if possible
3984  */
3985 int dasd_generic_requeue_all_requests(struct dasd_device *device)
3986 {
3987 	struct dasd_block *block = device->block;
3988 	struct list_head requeue_queue;
3989 	struct dasd_ccw_req *cqr, *n;
3990 	int rc;
3991 
3992 	if (!block)
3993 		return 0;
3994 
3995 	INIT_LIST_HEAD(&requeue_queue);
3996 	rc = _dasd_requests_to_flushqueue(block, &requeue_queue);
3997 
3998 	/* Now call the callback function of flushed requests */
3999 restart_cb:
4000 	list_for_each_entry_safe(cqr, n, &requeue_queue, blocklist) {
4001 		wait_event(dasd_flush_wq, (cqr->status < DASD_CQR_QUEUED));
4002 		/* Process finished ERP request. */
4003 		if (cqr->refers) {
4004 			spin_lock_bh(&block->queue_lock);
4005 			__dasd_process_erp(block->base, cqr);
4006 			spin_unlock_bh(&block->queue_lock);
4007 			/* restart list_for_xx loop since dasd_process_erp
4008 			 * might remove multiple elements
4009 			 */
4010 			goto restart_cb;
4011 		}
4012 		/*
4013 		 * An aborted request was replaced by a full-track write and is
4014 		 * retired by that replacement; do not requeue it, just release
4015 		 * it (mirrors the DASD_CQR_ABORTED handling in
4016 		 * __dasd_cleanup_cqr()).
4017 		 */
4018 		if (cqr->status == DASD_CQR_ABORTED) {
4019 			struct request *req = cqr->callback_data;
4020 
4021 			list_del_init(&cqr->blocklist);
4022 			cqr->block->base->discipline->free_cp(cqr, req);
4023 			continue;
4024 		}
4025 		_dasd_requeue_request(cqr);
4026 		list_del_init(&cqr->blocklist);
4027 		cqr->block->base->discipline->free_cp(
4028 			cqr, (struct request *) cqr->callback_data);
4029 	}
4030 	dasd_schedule_device_bh(device);
4031 	return rc;
4032 }
4033 EXPORT_SYMBOL_GPL(dasd_generic_requeue_all_requests);
4034 
4035 static void do_requeue_requests(struct work_struct *work)
4036 {
4037 	struct dasd_device *device = container_of(work, struct dasd_device,
4038 						  requeue_requests);
4039 	dasd_generic_requeue_all_requests(device);
4040 	dasd_device_remove_stop_bits(device, DASD_STOPPED_NOT_ACC);
4041 	if (device->block)
4042 		dasd_schedule_block_bh(device->block);
4043 	dasd_put_device(device);
4044 }
4045 
4046 void dasd_schedule_requeue(struct dasd_device *device)
4047 {
4048 	dasd_get_device(device);
4049 	/* queue call to dasd_reload_device to the kernel event daemon. */
4050 	if (!schedule_work(&device->requeue_requests))
4051 		dasd_put_device(device);
4052 }
4053 EXPORT_SYMBOL(dasd_schedule_requeue);
4054 
4055 static int dasd_handle_autoquiesce(struct dasd_device *device,
4056 				   struct dasd_ccw_req *cqr,
4057 				   unsigned int reason)
4058 {
4059 	/* in any case write eer message with reason */
4060 	if (dasd_eer_enabled(device))
4061 		dasd_eer_write(device, cqr, reason);
4062 
4063 	if (!test_bit(reason, &device->aq_mask))
4064 		return 0;
4065 
4066 	/* notify eer about autoquiesce */
4067 	if (dasd_eer_enabled(device))
4068 		dasd_eer_write(device, NULL, DASD_EER_AUTOQUIESCE);
4069 
4070 	dev_info(&device->cdev->dev,
4071 		 "The DASD has been put in the quiesce state\n");
4072 	dasd_device_set_stop_bits(device, DASD_STOPPED_QUIESCE);
4073 
4074 	if (device->features & DASD_FEATURE_REQUEUEQUIESCE)
4075 		dasd_schedule_requeue(device);
4076 
4077 	return 1;
4078 }
4079 
4080 static struct dasd_ccw_req *dasd_generic_build_rdc(struct dasd_device *device,
4081 						   int rdc_buffer_size,
4082 						   int magic)
4083 {
4084 	struct dasd_ccw_req *cqr;
4085 	struct ccw1 *ccw;
4086 
4087 	cqr = dasd_smalloc_request(magic, 1 /* RDC */, rdc_buffer_size, device,
4088 				   NULL);
4089 
4090 	if (IS_ERR(cqr)) {
4091 		DBF_EVENT_DEVID(DBF_WARNING, device->cdev, "%s",
4092 				"Could not allocate RDC request");
4093 		return cqr;
4094 	}
4095 
4096 	ccw = cqr->cpaddr;
4097 	ccw->cmd_code = CCW_CMD_RDC;
4098 	ccw->cda = virt_to_dma32(cqr->data);
4099 	ccw->flags = 0;
4100 	ccw->count = rdc_buffer_size;
4101 	cqr->startdev = device;
4102 	cqr->memdev = device;
4103 	cqr->expires = 10*HZ;
4104 	cqr->retries = 256;
4105 	cqr->buildclk = get_tod_clock();
4106 	cqr->status = DASD_CQR_FILLED;
4107 	return cqr;
4108 }
4109 
4110 
4111 int dasd_generic_read_dev_chars(struct dasd_device *device, int magic,
4112 				void *rdc_buffer, int rdc_buffer_size)
4113 {
4114 	int ret;
4115 	struct dasd_ccw_req *cqr;
4116 
4117 	cqr = dasd_generic_build_rdc(device, rdc_buffer_size, magic);
4118 	if (IS_ERR(cqr))
4119 		return PTR_ERR(cqr);
4120 
4121 	ret = dasd_sleep_on(cqr);
4122 	if (ret == 0)
4123 		memcpy(rdc_buffer, cqr->data, rdc_buffer_size);
4124 	dasd_sfree_request(cqr, cqr->memdev);
4125 	return ret;
4126 }
4127 EXPORT_SYMBOL_GPL(dasd_generic_read_dev_chars);
4128 
4129 /*
4130  *   In command mode and transport mode we need to look for sense
4131  *   data in different places. The sense data itself is allways
4132  *   an array of 32 bytes, so we can unify the sense data access
4133  *   for both modes.
4134  */
4135 char *dasd_get_sense(struct irb *irb)
4136 {
4137 	struct tsb *tsb = NULL;
4138 	char *sense = NULL;
4139 
4140 	if (scsw_is_tm(&irb->scsw) && (irb->scsw.tm.fcxs == 0x01)) {
4141 		if (irb->scsw.tm.tcw)
4142 			tsb = tcw_get_tsb(dma32_to_virt(irb->scsw.tm.tcw));
4143 		if (tsb && tsb->length == 64 && tsb->flags)
4144 			switch (tsb->flags & 0x07) {
4145 			case 1:	/* tsa_iostat */
4146 				sense = tsb->tsa.iostat.sense;
4147 				break;
4148 			case 2: /* tsa_ddpc */
4149 				sense = tsb->tsa.ddpc.sense;
4150 				break;
4151 			default:
4152 				/* currently we don't use interrogate data */
4153 				break;
4154 			}
4155 	} else if (irb->esw.esw0.erw.cons) {
4156 		sense = irb->ecw;
4157 	}
4158 	return sense;
4159 }
4160 EXPORT_SYMBOL_GPL(dasd_get_sense);
4161 
4162 void dasd_generic_shutdown(struct ccw_device *cdev)
4163 {
4164 	struct dasd_device *device;
4165 
4166 	device = dasd_device_from_cdev(cdev);
4167 	if (IS_ERR(device))
4168 		return;
4169 
4170 	if (device->block)
4171 		dasd_schedule_block_bh(device->block);
4172 
4173 	dasd_schedule_device_bh(device);
4174 
4175 	wait_event(shutdown_waitq, _wait_for_empty_queues(device));
4176 }
4177 EXPORT_SYMBOL_GPL(dasd_generic_shutdown);
4178 
4179 static int __init dasd_init(void)
4180 {
4181 	int rc;
4182 
4183 	init_waitqueue_head(&dasd_init_waitq);
4184 	init_waitqueue_head(&dasd_flush_wq);
4185 	init_waitqueue_head(&generic_waitq);
4186 	init_waitqueue_head(&shutdown_waitq);
4187 
4188 	/* register 'common' DASD debug area, used for all DBF_XXX calls */
4189 	dasd_debug_area = debug_register("dasd", 1, 1, 8 * sizeof(long));
4190 	if (dasd_debug_area == NULL) {
4191 		rc = -ENOMEM;
4192 		goto failed;
4193 	}
4194 	debug_register_view(dasd_debug_area, &debug_sprintf_view);
4195 	debug_set_level(dasd_debug_area, DBF_WARNING);
4196 
4197 	DBF_EVENT(DBF_EMERG, "%s", "debug area created");
4198 
4199 	dasd_diag_discipline_pointer = NULL;
4200 
4201 	dasd_statistics_createroot();
4202 
4203 	rc = dasd_devmap_init();
4204 	if (rc)
4205 		goto failed;
4206 	rc = dasd_gendisk_init();
4207 	if (rc)
4208 		goto failed;
4209 	rc = dasd_parse();
4210 	if (rc)
4211 		goto failed;
4212 	rc = dasd_eer_init();
4213 	if (rc)
4214 		goto failed;
4215 #ifdef CONFIG_PROC_FS
4216 	rc = dasd_proc_init();
4217 	if (rc)
4218 		goto failed;
4219 #endif
4220 
4221 	return 0;
4222 failed:
4223 	pr_info("The DASD device driver could not be initialized\n");
4224 	dasd_exit();
4225 	return rc;
4226 }
4227 
4228 module_init(dasd_init);
4229 module_exit(dasd_exit);
4230