xref: /openbmc/linux/drivers/block/drbd/drbd_req.c (revision d2999e1b)
1 /*
2    drbd_req.c
3 
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5 
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9 
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14 
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23 
24  */
25 
26 #include <linux/module.h>
27 
28 #include <linux/slab.h>
29 #include <linux/drbd.h>
30 #include "drbd_int.h"
31 #include "drbd_req.h"
32 
33 
34 static bool drbd_may_do_local_read(struct drbd_device *device, sector_t sector, int size);
35 
36 /* Update disk stats at start of I/O request */
37 static void _drbd_start_io_acct(struct drbd_device *device, struct drbd_request *req)
38 {
39 	const int rw = bio_data_dir(req->master_bio);
40 	int cpu;
41 	cpu = part_stat_lock();
42 	part_round_stats(cpu, &device->vdisk->part0);
43 	part_stat_inc(cpu, &device->vdisk->part0, ios[rw]);
44 	part_stat_add(cpu, &device->vdisk->part0, sectors[rw], req->i.size >> 9);
45 	(void) cpu; /* The macro invocations above want the cpu argument, I do not like
46 		       the compiler warning about cpu only assigned but never used... */
47 	part_inc_in_flight(&device->vdisk->part0, rw);
48 	part_stat_unlock();
49 }
50 
51 /* Update disk stats when completing request upwards */
52 static void _drbd_end_io_acct(struct drbd_device *device, struct drbd_request *req)
53 {
54 	int rw = bio_data_dir(req->master_bio);
55 	unsigned long duration = jiffies - req->start_time;
56 	int cpu;
57 	cpu = part_stat_lock();
58 	part_stat_add(cpu, &device->vdisk->part0, ticks[rw], duration);
59 	part_round_stats(cpu, &device->vdisk->part0);
60 	part_dec_in_flight(&device->vdisk->part0, rw);
61 	part_stat_unlock();
62 }
63 
64 static struct drbd_request *drbd_req_new(struct drbd_device *device,
65 					       struct bio *bio_src)
66 {
67 	struct drbd_request *req;
68 
69 	req = mempool_alloc(drbd_request_mempool, GFP_NOIO);
70 	if (!req)
71 		return NULL;
72 
73 	drbd_req_make_private_bio(req, bio_src);
74 	req->rq_state    = bio_data_dir(bio_src) == WRITE ? RQ_WRITE : 0;
75 	req->device   = device;
76 	req->master_bio  = bio_src;
77 	req->epoch       = 0;
78 
79 	drbd_clear_interval(&req->i);
80 	req->i.sector     = bio_src->bi_iter.bi_sector;
81 	req->i.size      = bio_src->bi_iter.bi_size;
82 	req->i.local = true;
83 	req->i.waiting = false;
84 
85 	INIT_LIST_HEAD(&req->tl_requests);
86 	INIT_LIST_HEAD(&req->w.list);
87 
88 	/* one reference to be put by __drbd_make_request */
89 	atomic_set(&req->completion_ref, 1);
90 	/* one kref as long as completion_ref > 0 */
91 	kref_init(&req->kref);
92 	return req;
93 }
94 
95 void drbd_req_destroy(struct kref *kref)
96 {
97 	struct drbd_request *req = container_of(kref, struct drbd_request, kref);
98 	struct drbd_device *device = req->device;
99 	const unsigned s = req->rq_state;
100 
101 	if ((req->master_bio && !(s & RQ_POSTPONED)) ||
102 		atomic_read(&req->completion_ref) ||
103 		(s & RQ_LOCAL_PENDING) ||
104 		((s & RQ_NET_MASK) && !(s & RQ_NET_DONE))) {
105 		drbd_err(device, "drbd_req_destroy: Logic BUG rq_state = 0x%x, completion_ref = %d\n",
106 				s, atomic_read(&req->completion_ref));
107 		return;
108 	}
109 
110 	/* remove it from the transfer log.
111 	 * well, only if it had been there in the first
112 	 * place... if it had not (local only or conflicting
113 	 * and never sent), it should still be "empty" as
114 	 * initialized in drbd_req_new(), so we can list_del() it
115 	 * here unconditionally */
116 	list_del_init(&req->tl_requests);
117 
118 	/* if it was a write, we may have to set the corresponding
119 	 * bit(s) out-of-sync first. If it had a local part, we need to
120 	 * release the reference to the activity log. */
121 	if (s & RQ_WRITE) {
122 		/* Set out-of-sync unless both OK flags are set
123 		 * (local only or remote failed).
124 		 * Other places where we set out-of-sync:
125 		 * READ with local io-error */
126 
127 		/* There is a special case:
128 		 * we may notice late that IO was suspended,
129 		 * and postpone, or schedule for retry, a write,
130 		 * before it even was submitted or sent.
131 		 * In that case we do not want to touch the bitmap at all.
132 		 */
133 		if ((s & (RQ_POSTPONED|RQ_LOCAL_MASK|RQ_NET_MASK)) != RQ_POSTPONED) {
134 			if (!(s & RQ_NET_OK) || !(s & RQ_LOCAL_OK))
135 				drbd_set_out_of_sync(device, req->i.sector, req->i.size);
136 
137 			if ((s & RQ_NET_OK) && (s & RQ_LOCAL_OK) && (s & RQ_NET_SIS))
138 				drbd_set_in_sync(device, req->i.sector, req->i.size);
139 		}
140 
141 		/* one might be tempted to move the drbd_al_complete_io
142 		 * to the local io completion callback drbd_request_endio.
143 		 * but, if this was a mirror write, we may only
144 		 * drbd_al_complete_io after this is RQ_NET_DONE,
145 		 * otherwise the extent could be dropped from the al
146 		 * before it has actually been written on the peer.
147 		 * if we crash before our peer knows about the request,
148 		 * but after the extent has been dropped from the al,
149 		 * we would forget to resync the corresponding extent.
150 		 */
151 		if (s & RQ_IN_ACT_LOG) {
152 			if (get_ldev_if_state(device, D_FAILED)) {
153 				drbd_al_complete_io(device, &req->i);
154 				put_ldev(device);
155 			} else if (__ratelimit(&drbd_ratelimit_state)) {
156 				drbd_warn(device, "Should have called drbd_al_complete_io(, %llu, %u), "
157 					 "but my Disk seems to have failed :(\n",
158 					 (unsigned long long) req->i.sector, req->i.size);
159 			}
160 		}
161 	}
162 
163 	mempool_free(req, drbd_request_mempool);
164 }
165 
166 static void wake_all_senders(struct drbd_connection *connection)
167 {
168 	wake_up(&connection->sender_work.q_wait);
169 }
170 
171 /* must hold resource->req_lock */
172 void start_new_tl_epoch(struct drbd_connection *connection)
173 {
174 	/* no point closing an epoch, if it is empty, anyways. */
175 	if (connection->current_tle_writes == 0)
176 		return;
177 
178 	connection->current_tle_writes = 0;
179 	atomic_inc(&connection->current_tle_nr);
180 	wake_all_senders(connection);
181 }
182 
183 void complete_master_bio(struct drbd_device *device,
184 		struct bio_and_error *m)
185 {
186 	bio_endio(m->bio, m->error);
187 	dec_ap_bio(device);
188 }
189 
190 
191 static void drbd_remove_request_interval(struct rb_root *root,
192 					 struct drbd_request *req)
193 {
194 	struct drbd_device *device = req->device;
195 	struct drbd_interval *i = &req->i;
196 
197 	drbd_remove_interval(root, i);
198 
199 	/* Wake up any processes waiting for this request to complete.  */
200 	if (i->waiting)
201 		wake_up(&device->misc_wait);
202 }
203 
204 /* Helper for __req_mod().
205  * Set m->bio to the master bio, if it is fit to be completed,
206  * or leave it alone (it is initialized to NULL in __req_mod),
207  * if it has already been completed, or cannot be completed yet.
208  * If m->bio is set, the error status to be returned is placed in m->error.
209  */
210 static
211 void drbd_req_complete(struct drbd_request *req, struct bio_and_error *m)
212 {
213 	const unsigned s = req->rq_state;
214 	struct drbd_device *device = req->device;
215 	int rw;
216 	int error, ok;
217 
218 	/* we must not complete the master bio, while it is
219 	 *	still being processed by _drbd_send_zc_bio (drbd_send_dblock)
220 	 *	not yet acknowledged by the peer
221 	 *	not yet completed by the local io subsystem
222 	 * these flags may get cleared in any order by
223 	 *	the worker,
224 	 *	the receiver,
225 	 *	the bio_endio completion callbacks.
226 	 */
227 	if ((s & RQ_LOCAL_PENDING && !(s & RQ_LOCAL_ABORTED)) ||
228 	    (s & RQ_NET_QUEUED) || (s & RQ_NET_PENDING) ||
229 	    (s & RQ_COMPLETION_SUSP)) {
230 		drbd_err(device, "drbd_req_complete: Logic BUG rq_state = 0x%x\n", s);
231 		return;
232 	}
233 
234 	if (!req->master_bio) {
235 		drbd_err(device, "drbd_req_complete: Logic BUG, master_bio == NULL!\n");
236 		return;
237 	}
238 
239 	rw = bio_rw(req->master_bio);
240 
241 	/*
242 	 * figure out whether to report success or failure.
243 	 *
244 	 * report success when at least one of the operations succeeded.
245 	 * or, to put the other way,
246 	 * only report failure, when both operations failed.
247 	 *
248 	 * what to do about the failures is handled elsewhere.
249 	 * what we need to do here is just: complete the master_bio.
250 	 *
251 	 * local completion error, if any, has been stored as ERR_PTR
252 	 * in private_bio within drbd_request_endio.
253 	 */
254 	ok = (s & RQ_LOCAL_OK) || (s & RQ_NET_OK);
255 	error = PTR_ERR(req->private_bio);
256 
257 	/* remove the request from the conflict detection
258 	 * respective block_id verification hash */
259 	if (!drbd_interval_empty(&req->i)) {
260 		struct rb_root *root;
261 
262 		if (rw == WRITE)
263 			root = &device->write_requests;
264 		else
265 			root = &device->read_requests;
266 		drbd_remove_request_interval(root, req);
267 	}
268 
269 	/* Before we can signal completion to the upper layers,
270 	 * we may need to close the current transfer log epoch.
271 	 * We are within the request lock, so we can simply compare
272 	 * the request epoch number with the current transfer log
273 	 * epoch number.  If they match, increase the current_tle_nr,
274 	 * and reset the transfer log epoch write_cnt.
275 	 */
276 	if (rw == WRITE &&
277 	    req->epoch == atomic_read(&first_peer_device(device)->connection->current_tle_nr))
278 		start_new_tl_epoch(first_peer_device(device)->connection);
279 
280 	/* Update disk stats */
281 	_drbd_end_io_acct(device, req);
282 
283 	/* If READ failed,
284 	 * have it be pushed back to the retry work queue,
285 	 * so it will re-enter __drbd_make_request(),
286 	 * and be re-assigned to a suitable local or remote path,
287 	 * or failed if we do not have access to good data anymore.
288 	 *
289 	 * Unless it was failed early by __drbd_make_request(),
290 	 * because no path was available, in which case
291 	 * it was not even added to the transfer_log.
292 	 *
293 	 * READA may fail, and will not be retried.
294 	 *
295 	 * WRITE should have used all available paths already.
296 	 */
297 	if (!ok && rw == READ && !list_empty(&req->tl_requests))
298 		req->rq_state |= RQ_POSTPONED;
299 
300 	if (!(req->rq_state & RQ_POSTPONED)) {
301 		m->error = ok ? 0 : (error ?: -EIO);
302 		m->bio = req->master_bio;
303 		req->master_bio = NULL;
304 	}
305 }
306 
307 static int drbd_req_put_completion_ref(struct drbd_request *req, struct bio_and_error *m, int put)
308 {
309 	struct drbd_device *device = req->device;
310 	D_ASSERT(device, m || (req->rq_state & RQ_POSTPONED));
311 
312 	if (!atomic_sub_and_test(put, &req->completion_ref))
313 		return 0;
314 
315 	drbd_req_complete(req, m);
316 
317 	if (req->rq_state & RQ_POSTPONED) {
318 		/* don't destroy the req object just yet,
319 		 * but queue it for retry */
320 		drbd_restart_request(req);
321 		return 0;
322 	}
323 
324 	return 1;
325 }
326 
327 /* I'd like this to be the only place that manipulates
328  * req->completion_ref and req->kref. */
329 static void mod_rq_state(struct drbd_request *req, struct bio_and_error *m,
330 		int clear, int set)
331 {
332 	struct drbd_device *device = req->device;
333 	unsigned s = req->rq_state;
334 	int c_put = 0;
335 	int k_put = 0;
336 
337 	if (drbd_suspended(device) && !((s | clear) & RQ_COMPLETION_SUSP))
338 		set |= RQ_COMPLETION_SUSP;
339 
340 	/* apply */
341 
342 	req->rq_state &= ~clear;
343 	req->rq_state |= set;
344 
345 	/* no change? */
346 	if (req->rq_state == s)
347 		return;
348 
349 	/* intent: get references */
350 
351 	if (!(s & RQ_LOCAL_PENDING) && (set & RQ_LOCAL_PENDING))
352 		atomic_inc(&req->completion_ref);
353 
354 	if (!(s & RQ_NET_PENDING) && (set & RQ_NET_PENDING)) {
355 		inc_ap_pending(device);
356 		atomic_inc(&req->completion_ref);
357 	}
358 
359 	if (!(s & RQ_NET_QUEUED) && (set & RQ_NET_QUEUED))
360 		atomic_inc(&req->completion_ref);
361 
362 	if (!(s & RQ_EXP_BARR_ACK) && (set & RQ_EXP_BARR_ACK))
363 		kref_get(&req->kref); /* wait for the DONE */
364 
365 	if (!(s & RQ_NET_SENT) && (set & RQ_NET_SENT))
366 		atomic_add(req->i.size >> 9, &device->ap_in_flight);
367 
368 	if (!(s & RQ_COMPLETION_SUSP) && (set & RQ_COMPLETION_SUSP))
369 		atomic_inc(&req->completion_ref);
370 
371 	/* progress: put references */
372 
373 	if ((s & RQ_COMPLETION_SUSP) && (clear & RQ_COMPLETION_SUSP))
374 		++c_put;
375 
376 	if (!(s & RQ_LOCAL_ABORTED) && (set & RQ_LOCAL_ABORTED)) {
377 		D_ASSERT(device, req->rq_state & RQ_LOCAL_PENDING);
378 		/* local completion may still come in later,
379 		 * we need to keep the req object around. */
380 		kref_get(&req->kref);
381 		++c_put;
382 	}
383 
384 	if ((s & RQ_LOCAL_PENDING) && (clear & RQ_LOCAL_PENDING)) {
385 		if (req->rq_state & RQ_LOCAL_ABORTED)
386 			++k_put;
387 		else
388 			++c_put;
389 	}
390 
391 	if ((s & RQ_NET_PENDING) && (clear & RQ_NET_PENDING)) {
392 		dec_ap_pending(device);
393 		++c_put;
394 	}
395 
396 	if ((s & RQ_NET_QUEUED) && (clear & RQ_NET_QUEUED))
397 		++c_put;
398 
399 	if ((s & RQ_EXP_BARR_ACK) && !(s & RQ_NET_DONE) && (set & RQ_NET_DONE)) {
400 		if (req->rq_state & RQ_NET_SENT)
401 			atomic_sub(req->i.size >> 9, &device->ap_in_flight);
402 		++k_put;
403 	}
404 
405 	/* potentially complete and destroy */
406 
407 	if (k_put || c_put) {
408 		/* Completion does it's own kref_put.  If we are going to
409 		 * kref_sub below, we need req to be still around then. */
410 		int at_least = k_put + !!c_put;
411 		int refcount = atomic_read(&req->kref.refcount);
412 		if (refcount < at_least)
413 			drbd_err(device,
414 				"mod_rq_state: Logic BUG: %x -> %x: refcount = %d, should be >= %d\n",
415 				s, req->rq_state, refcount, at_least);
416 	}
417 
418 	/* If we made progress, retry conflicting peer requests, if any. */
419 	if (req->i.waiting)
420 		wake_up(&device->misc_wait);
421 
422 	if (c_put)
423 		k_put += drbd_req_put_completion_ref(req, m, c_put);
424 	if (k_put)
425 		kref_sub(&req->kref, k_put, drbd_req_destroy);
426 }
427 
428 static void drbd_report_io_error(struct drbd_device *device, struct drbd_request *req)
429 {
430         char b[BDEVNAME_SIZE];
431 
432 	if (!__ratelimit(&drbd_ratelimit_state))
433 		return;
434 
435 	drbd_warn(device, "local %s IO error sector %llu+%u on %s\n",
436 			(req->rq_state & RQ_WRITE) ? "WRITE" : "READ",
437 			(unsigned long long)req->i.sector,
438 			req->i.size >> 9,
439 			bdevname(device->ldev->backing_bdev, b));
440 }
441 
442 /* obviously this could be coded as many single functions
443  * instead of one huge switch,
444  * or by putting the code directly in the respective locations
445  * (as it has been before).
446  *
447  * but having it this way
448  *  enforces that it is all in this one place, where it is easier to audit,
449  *  it makes it obvious that whatever "event" "happens" to a request should
450  *  happen "atomically" within the req_lock,
451  *  and it enforces that we have to think in a very structured manner
452  *  about the "events" that may happen to a request during its life time ...
453  */
454 int __req_mod(struct drbd_request *req, enum drbd_req_event what,
455 		struct bio_and_error *m)
456 {
457 	struct drbd_device *device = req->device;
458 	struct net_conf *nc;
459 	int p, rv = 0;
460 
461 	if (m)
462 		m->bio = NULL;
463 
464 	switch (what) {
465 	default:
466 		drbd_err(device, "LOGIC BUG in %s:%u\n", __FILE__ , __LINE__);
467 		break;
468 
469 	/* does not happen...
470 	 * initialization done in drbd_req_new
471 	case CREATED:
472 		break;
473 		*/
474 
475 	case TO_BE_SENT: /* via network */
476 		/* reached via __drbd_make_request
477 		 * and from w_read_retry_remote */
478 		D_ASSERT(device, !(req->rq_state & RQ_NET_MASK));
479 		rcu_read_lock();
480 		nc = rcu_dereference(first_peer_device(device)->connection->net_conf);
481 		p = nc->wire_protocol;
482 		rcu_read_unlock();
483 		req->rq_state |=
484 			p == DRBD_PROT_C ? RQ_EXP_WRITE_ACK :
485 			p == DRBD_PROT_B ? RQ_EXP_RECEIVE_ACK : 0;
486 		mod_rq_state(req, m, 0, RQ_NET_PENDING);
487 		break;
488 
489 	case TO_BE_SUBMITTED: /* locally */
490 		/* reached via __drbd_make_request */
491 		D_ASSERT(device, !(req->rq_state & RQ_LOCAL_MASK));
492 		mod_rq_state(req, m, 0, RQ_LOCAL_PENDING);
493 		break;
494 
495 	case COMPLETED_OK:
496 		if (req->rq_state & RQ_WRITE)
497 			device->writ_cnt += req->i.size >> 9;
498 		else
499 			device->read_cnt += req->i.size >> 9;
500 
501 		mod_rq_state(req, m, RQ_LOCAL_PENDING,
502 				RQ_LOCAL_COMPLETED|RQ_LOCAL_OK);
503 		break;
504 
505 	case ABORT_DISK_IO:
506 		mod_rq_state(req, m, 0, RQ_LOCAL_ABORTED);
507 		break;
508 
509 	case WRITE_COMPLETED_WITH_ERROR:
510 		drbd_report_io_error(device, req);
511 		__drbd_chk_io_error(device, DRBD_WRITE_ERROR);
512 		mod_rq_state(req, m, RQ_LOCAL_PENDING, RQ_LOCAL_COMPLETED);
513 		break;
514 
515 	case READ_COMPLETED_WITH_ERROR:
516 		drbd_set_out_of_sync(device, req->i.sector, req->i.size);
517 		drbd_report_io_error(device, req);
518 		__drbd_chk_io_error(device, DRBD_READ_ERROR);
519 		/* fall through. */
520 	case READ_AHEAD_COMPLETED_WITH_ERROR:
521 		/* it is legal to fail READA, no __drbd_chk_io_error in that case. */
522 		mod_rq_state(req, m, RQ_LOCAL_PENDING, RQ_LOCAL_COMPLETED);
523 		break;
524 
525 	case DISCARD_COMPLETED_NOTSUPP:
526 	case DISCARD_COMPLETED_WITH_ERROR:
527 		/* I'd rather not detach from local disk just because it
528 		 * failed a REQ_DISCARD. */
529 		mod_rq_state(req, m, RQ_LOCAL_PENDING, RQ_LOCAL_COMPLETED);
530 		break;
531 
532 	case QUEUE_FOR_NET_READ:
533 		/* READ or READA, and
534 		 * no local disk,
535 		 * or target area marked as invalid,
536 		 * or just got an io-error. */
537 		/* from __drbd_make_request
538 		 * or from bio_endio during read io-error recovery */
539 
540 		/* So we can verify the handle in the answer packet.
541 		 * Corresponding drbd_remove_request_interval is in
542 		 * drbd_req_complete() */
543 		D_ASSERT(device, drbd_interval_empty(&req->i));
544 		drbd_insert_interval(&device->read_requests, &req->i);
545 
546 		set_bit(UNPLUG_REMOTE, &device->flags);
547 
548 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
549 		D_ASSERT(device, (req->rq_state & RQ_LOCAL_MASK) == 0);
550 		mod_rq_state(req, m, 0, RQ_NET_QUEUED);
551 		req->w.cb = w_send_read_req;
552 		drbd_queue_work(&first_peer_device(device)->connection->sender_work,
553 				&req->w);
554 		break;
555 
556 	case QUEUE_FOR_NET_WRITE:
557 		/* assert something? */
558 		/* from __drbd_make_request only */
559 
560 		/* Corresponding drbd_remove_request_interval is in
561 		 * drbd_req_complete() */
562 		D_ASSERT(device, drbd_interval_empty(&req->i));
563 		drbd_insert_interval(&device->write_requests, &req->i);
564 
565 		/* NOTE
566 		 * In case the req ended up on the transfer log before being
567 		 * queued on the worker, it could lead to this request being
568 		 * missed during cleanup after connection loss.
569 		 * So we have to do both operations here,
570 		 * within the same lock that protects the transfer log.
571 		 *
572 		 * _req_add_to_epoch(req); this has to be after the
573 		 * _maybe_start_new_epoch(req); which happened in
574 		 * __drbd_make_request, because we now may set the bit
575 		 * again ourselves to close the current epoch.
576 		 *
577 		 * Add req to the (now) current epoch (barrier). */
578 
579 		/* otherwise we may lose an unplug, which may cause some remote
580 		 * io-scheduler timeout to expire, increasing maximum latency,
581 		 * hurting performance. */
582 		set_bit(UNPLUG_REMOTE, &device->flags);
583 
584 		/* queue work item to send data */
585 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
586 		mod_rq_state(req, m, 0, RQ_NET_QUEUED|RQ_EXP_BARR_ACK);
587 		req->w.cb =  w_send_dblock;
588 		drbd_queue_work(&first_peer_device(device)->connection->sender_work,
589 				&req->w);
590 
591 		/* close the epoch, in case it outgrew the limit */
592 		rcu_read_lock();
593 		nc = rcu_dereference(first_peer_device(device)->connection->net_conf);
594 		p = nc->max_epoch_size;
595 		rcu_read_unlock();
596 		if (first_peer_device(device)->connection->current_tle_writes >= p)
597 			start_new_tl_epoch(first_peer_device(device)->connection);
598 
599 		break;
600 
601 	case QUEUE_FOR_SEND_OOS:
602 		mod_rq_state(req, m, 0, RQ_NET_QUEUED);
603 		req->w.cb =  w_send_out_of_sync;
604 		drbd_queue_work(&first_peer_device(device)->connection->sender_work,
605 				&req->w);
606 		break;
607 
608 	case READ_RETRY_REMOTE_CANCELED:
609 	case SEND_CANCELED:
610 	case SEND_FAILED:
611 		/* real cleanup will be done from tl_clear.  just update flags
612 		 * so it is no longer marked as on the worker queue */
613 		mod_rq_state(req, m, RQ_NET_QUEUED, 0);
614 		break;
615 
616 	case HANDED_OVER_TO_NETWORK:
617 		/* assert something? */
618 		if (bio_data_dir(req->master_bio) == WRITE &&
619 		    !(req->rq_state & (RQ_EXP_RECEIVE_ACK | RQ_EXP_WRITE_ACK))) {
620 			/* this is what is dangerous about protocol A:
621 			 * pretend it was successfully written on the peer. */
622 			if (req->rq_state & RQ_NET_PENDING)
623 				mod_rq_state(req, m, RQ_NET_PENDING, RQ_NET_OK);
624 			/* else: neg-ack was faster... */
625 			/* it is still not yet RQ_NET_DONE until the
626 			 * corresponding epoch barrier got acked as well,
627 			 * so we know what to dirty on connection loss */
628 		}
629 		mod_rq_state(req, m, RQ_NET_QUEUED, RQ_NET_SENT);
630 		break;
631 
632 	case OOS_HANDED_TO_NETWORK:
633 		/* Was not set PENDING, no longer QUEUED, so is now DONE
634 		 * as far as this connection is concerned. */
635 		mod_rq_state(req, m, RQ_NET_QUEUED, RQ_NET_DONE);
636 		break;
637 
638 	case CONNECTION_LOST_WHILE_PENDING:
639 		/* transfer log cleanup after connection loss */
640 		mod_rq_state(req, m,
641 				RQ_NET_OK|RQ_NET_PENDING|RQ_COMPLETION_SUSP,
642 				RQ_NET_DONE);
643 		break;
644 
645 	case CONFLICT_RESOLVED:
646 		/* for superseded conflicting writes of multiple primaries,
647 		 * there is no need to keep anything in the tl, potential
648 		 * node crashes are covered by the activity log.
649 		 *
650 		 * If this request had been marked as RQ_POSTPONED before,
651 		 * it will actually not be completed, but "restarted",
652 		 * resubmitted from the retry worker context. */
653 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
654 		D_ASSERT(device, req->rq_state & RQ_EXP_WRITE_ACK);
655 		mod_rq_state(req, m, RQ_NET_PENDING, RQ_NET_DONE|RQ_NET_OK);
656 		break;
657 
658 	case WRITE_ACKED_BY_PEER_AND_SIS:
659 		req->rq_state |= RQ_NET_SIS;
660 	case WRITE_ACKED_BY_PEER:
661 		D_ASSERT(device, req->rq_state & RQ_EXP_WRITE_ACK);
662 		/* protocol C; successfully written on peer.
663 		 * Nothing more to do here.
664 		 * We want to keep the tl in place for all protocols, to cater
665 		 * for volatile write-back caches on lower level devices. */
666 
667 		goto ack_common;
668 	case RECV_ACKED_BY_PEER:
669 		D_ASSERT(device, req->rq_state & RQ_EXP_RECEIVE_ACK);
670 		/* protocol B; pretends to be successfully written on peer.
671 		 * see also notes above in HANDED_OVER_TO_NETWORK about
672 		 * protocol != C */
673 	ack_common:
674 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
675 		mod_rq_state(req, m, RQ_NET_PENDING, RQ_NET_OK);
676 		break;
677 
678 	case POSTPONE_WRITE:
679 		D_ASSERT(device, req->rq_state & RQ_EXP_WRITE_ACK);
680 		/* If this node has already detected the write conflict, the
681 		 * worker will be waiting on misc_wait.  Wake it up once this
682 		 * request has completed locally.
683 		 */
684 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
685 		req->rq_state |= RQ_POSTPONED;
686 		if (req->i.waiting)
687 			wake_up(&device->misc_wait);
688 		/* Do not clear RQ_NET_PENDING. This request will make further
689 		 * progress via restart_conflicting_writes() or
690 		 * fail_postponed_requests(). Hopefully. */
691 		break;
692 
693 	case NEG_ACKED:
694 		mod_rq_state(req, m, RQ_NET_OK|RQ_NET_PENDING, 0);
695 		break;
696 
697 	case FAIL_FROZEN_DISK_IO:
698 		if (!(req->rq_state & RQ_LOCAL_COMPLETED))
699 			break;
700 		mod_rq_state(req, m, RQ_COMPLETION_SUSP, 0);
701 		break;
702 
703 	case RESTART_FROZEN_DISK_IO:
704 		if (!(req->rq_state & RQ_LOCAL_COMPLETED))
705 			break;
706 
707 		mod_rq_state(req, m,
708 				RQ_COMPLETION_SUSP|RQ_LOCAL_COMPLETED,
709 				RQ_LOCAL_PENDING);
710 
711 		rv = MR_READ;
712 		if (bio_data_dir(req->master_bio) == WRITE)
713 			rv = MR_WRITE;
714 
715 		get_ldev(device); /* always succeeds in this call path */
716 		req->w.cb = w_restart_disk_io;
717 		drbd_queue_work(&first_peer_device(device)->connection->sender_work,
718 				&req->w);
719 		break;
720 
721 	case RESEND:
722 		/* Simply complete (local only) READs. */
723 		if (!(req->rq_state & RQ_WRITE) && !req->w.cb) {
724 			mod_rq_state(req, m, RQ_COMPLETION_SUSP, 0);
725 			break;
726 		}
727 
728 		/* If RQ_NET_OK is already set, we got a P_WRITE_ACK or P_RECV_ACK
729 		   before the connection loss (B&C only); only P_BARRIER_ACK
730 		   (or the local completion?) was missing when we suspended.
731 		   Throwing them out of the TL here by pretending we got a BARRIER_ACK.
732 		   During connection handshake, we ensure that the peer was not rebooted. */
733 		if (!(req->rq_state & RQ_NET_OK)) {
734 			/* FIXME could this possibly be a req->dw.cb == w_send_out_of_sync?
735 			 * in that case we must not set RQ_NET_PENDING. */
736 
737 			mod_rq_state(req, m, RQ_COMPLETION_SUSP, RQ_NET_QUEUED|RQ_NET_PENDING);
738 			if (req->w.cb) {
739 				drbd_queue_work(&first_peer_device(device)->connection->sender_work,
740 						&req->w);
741 				rv = req->rq_state & RQ_WRITE ? MR_WRITE : MR_READ;
742 			} /* else: FIXME can this happen? */
743 			break;
744 		}
745 		/* else, fall through to BARRIER_ACKED */
746 
747 	case BARRIER_ACKED:
748 		/* barrier ack for READ requests does not make sense */
749 		if (!(req->rq_state & RQ_WRITE))
750 			break;
751 
752 		if (req->rq_state & RQ_NET_PENDING) {
753 			/* barrier came in before all requests were acked.
754 			 * this is bad, because if the connection is lost now,
755 			 * we won't be able to clean them up... */
756 			drbd_err(device, "FIXME (BARRIER_ACKED but pending)\n");
757 		}
758 		/* Allowed to complete requests, even while suspended.
759 		 * As this is called for all requests within a matching epoch,
760 		 * we need to filter, and only set RQ_NET_DONE for those that
761 		 * have actually been on the wire. */
762 		mod_rq_state(req, m, RQ_COMPLETION_SUSP,
763 				(req->rq_state & RQ_NET_MASK) ? RQ_NET_DONE : 0);
764 		break;
765 
766 	case DATA_RECEIVED:
767 		D_ASSERT(device, req->rq_state & RQ_NET_PENDING);
768 		mod_rq_state(req, m, RQ_NET_PENDING, RQ_NET_OK|RQ_NET_DONE);
769 		break;
770 
771 	case QUEUE_AS_DRBD_BARRIER:
772 		start_new_tl_epoch(first_peer_device(device)->connection);
773 		mod_rq_state(req, m, 0, RQ_NET_OK|RQ_NET_DONE);
774 		break;
775 	};
776 
777 	return rv;
778 }
779 
780 /* we may do a local read if:
781  * - we are consistent (of course),
782  * - or we are generally inconsistent,
783  *   BUT we are still/already IN SYNC for this area.
784  *   since size may be bigger than BM_BLOCK_SIZE,
785  *   we may need to check several bits.
786  */
787 static bool drbd_may_do_local_read(struct drbd_device *device, sector_t sector, int size)
788 {
789 	unsigned long sbnr, ebnr;
790 	sector_t esector, nr_sectors;
791 
792 	if (device->state.disk == D_UP_TO_DATE)
793 		return true;
794 	if (device->state.disk != D_INCONSISTENT)
795 		return false;
796 	esector = sector + (size >> 9) - 1;
797 	nr_sectors = drbd_get_capacity(device->this_bdev);
798 	D_ASSERT(device, sector  < nr_sectors);
799 	D_ASSERT(device, esector < nr_sectors);
800 
801 	sbnr = BM_SECT_TO_BIT(sector);
802 	ebnr = BM_SECT_TO_BIT(esector);
803 
804 	return drbd_bm_count_bits(device, sbnr, ebnr) == 0;
805 }
806 
807 static bool remote_due_to_read_balancing(struct drbd_device *device, sector_t sector,
808 		enum drbd_read_balancing rbm)
809 {
810 	struct backing_dev_info *bdi;
811 	int stripe_shift;
812 
813 	switch (rbm) {
814 	case RB_CONGESTED_REMOTE:
815 		bdi = &device->ldev->backing_bdev->bd_disk->queue->backing_dev_info;
816 		return bdi_read_congested(bdi);
817 	case RB_LEAST_PENDING:
818 		return atomic_read(&device->local_cnt) >
819 			atomic_read(&device->ap_pending_cnt) + atomic_read(&device->rs_pending_cnt);
820 	case RB_32K_STRIPING:  /* stripe_shift = 15 */
821 	case RB_64K_STRIPING:
822 	case RB_128K_STRIPING:
823 	case RB_256K_STRIPING:
824 	case RB_512K_STRIPING:
825 	case RB_1M_STRIPING:   /* stripe_shift = 20 */
826 		stripe_shift = (rbm - RB_32K_STRIPING + 15);
827 		return (sector >> (stripe_shift - 9)) & 1;
828 	case RB_ROUND_ROBIN:
829 		return test_and_change_bit(READ_BALANCE_RR, &device->flags);
830 	case RB_PREFER_REMOTE:
831 		return true;
832 	case RB_PREFER_LOCAL:
833 	default:
834 		return false;
835 	}
836 }
837 
838 /*
839  * complete_conflicting_writes  -  wait for any conflicting write requests
840  *
841  * The write_requests tree contains all active write requests which we
842  * currently know about.  Wait for any requests to complete which conflict with
843  * the new one.
844  *
845  * Only way out: remove the conflicting intervals from the tree.
846  */
847 static void complete_conflicting_writes(struct drbd_request *req)
848 {
849 	DEFINE_WAIT(wait);
850 	struct drbd_device *device = req->device;
851 	struct drbd_interval *i;
852 	sector_t sector = req->i.sector;
853 	int size = req->i.size;
854 
855 	i = drbd_find_overlap(&device->write_requests, sector, size);
856 	if (!i)
857 		return;
858 
859 	for (;;) {
860 		prepare_to_wait(&device->misc_wait, &wait, TASK_UNINTERRUPTIBLE);
861 		i = drbd_find_overlap(&device->write_requests, sector, size);
862 		if (!i)
863 			break;
864 		/* Indicate to wake up device->misc_wait on progress.  */
865 		i->waiting = true;
866 		spin_unlock_irq(&device->resource->req_lock);
867 		schedule();
868 		spin_lock_irq(&device->resource->req_lock);
869 	}
870 	finish_wait(&device->misc_wait, &wait);
871 }
872 
873 /* called within req_lock and rcu_read_lock() */
874 static void maybe_pull_ahead(struct drbd_device *device)
875 {
876 	struct drbd_connection *connection = first_peer_device(device)->connection;
877 	struct net_conf *nc;
878 	bool congested = false;
879 	enum drbd_on_congestion on_congestion;
880 
881 	rcu_read_lock();
882 	nc = rcu_dereference(connection->net_conf);
883 	on_congestion = nc ? nc->on_congestion : OC_BLOCK;
884 	rcu_read_unlock();
885 	if (on_congestion == OC_BLOCK ||
886 	    connection->agreed_pro_version < 96)
887 		return;
888 
889 	/* If I don't even have good local storage, we can not reasonably try
890 	 * to pull ahead of the peer. We also need the local reference to make
891 	 * sure device->act_log is there.
892 	 */
893 	if (!get_ldev_if_state(device, D_UP_TO_DATE))
894 		return;
895 
896 	if (nc->cong_fill &&
897 	    atomic_read(&device->ap_in_flight) >= nc->cong_fill) {
898 		drbd_info(device, "Congestion-fill threshold reached\n");
899 		congested = true;
900 	}
901 
902 	if (device->act_log->used >= nc->cong_extents) {
903 		drbd_info(device, "Congestion-extents threshold reached\n");
904 		congested = true;
905 	}
906 
907 	if (congested) {
908 		/* start a new epoch for non-mirrored writes */
909 		start_new_tl_epoch(first_peer_device(device)->connection);
910 
911 		if (on_congestion == OC_PULL_AHEAD)
912 			_drbd_set_state(_NS(device, conn, C_AHEAD), 0, NULL);
913 		else  /*nc->on_congestion == OC_DISCONNECT */
914 			_drbd_set_state(_NS(device, conn, C_DISCONNECTING), 0, NULL);
915 	}
916 	put_ldev(device);
917 }
918 
919 /* If this returns false, and req->private_bio is still set,
920  * this should be submitted locally.
921  *
922  * If it returns false, but req->private_bio is not set,
923  * we do not have access to good data :(
924  *
925  * Otherwise, this destroys req->private_bio, if any,
926  * and returns true.
927  */
928 static bool do_remote_read(struct drbd_request *req)
929 {
930 	struct drbd_device *device = req->device;
931 	enum drbd_read_balancing rbm;
932 
933 	if (req->private_bio) {
934 		if (!drbd_may_do_local_read(device,
935 					req->i.sector, req->i.size)) {
936 			bio_put(req->private_bio);
937 			req->private_bio = NULL;
938 			put_ldev(device);
939 		}
940 	}
941 
942 	if (device->state.pdsk != D_UP_TO_DATE)
943 		return false;
944 
945 	if (req->private_bio == NULL)
946 		return true;
947 
948 	/* TODO: improve read balancing decisions, take into account drbd
949 	 * protocol, pending requests etc. */
950 
951 	rcu_read_lock();
952 	rbm = rcu_dereference(device->ldev->disk_conf)->read_balancing;
953 	rcu_read_unlock();
954 
955 	if (rbm == RB_PREFER_LOCAL && req->private_bio)
956 		return false; /* submit locally */
957 
958 	if (remote_due_to_read_balancing(device, req->i.sector, rbm)) {
959 		if (req->private_bio) {
960 			bio_put(req->private_bio);
961 			req->private_bio = NULL;
962 			put_ldev(device);
963 		}
964 		return true;
965 	}
966 
967 	return false;
968 }
969 
970 /* returns number of connections (== 1, for drbd 8.4)
971  * expected to actually write this data,
972  * which does NOT include those that we are L_AHEAD for. */
973 static int drbd_process_write_request(struct drbd_request *req)
974 {
975 	struct drbd_device *device = req->device;
976 	int remote, send_oos;
977 
978 	remote = drbd_should_do_remote(device->state);
979 	send_oos = drbd_should_send_out_of_sync(device->state);
980 
981 	/* Need to replicate writes.  Unless it is an empty flush,
982 	 * which is better mapped to a DRBD P_BARRIER packet,
983 	 * also for drbd wire protocol compatibility reasons.
984 	 * If this was a flush, just start a new epoch.
985 	 * Unless the current epoch was empty anyways, or we are not currently
986 	 * replicating, in which case there is no point. */
987 	if (unlikely(req->i.size == 0)) {
988 		/* The only size==0 bios we expect are empty flushes. */
989 		D_ASSERT(device, req->master_bio->bi_rw & REQ_FLUSH);
990 		if (remote)
991 			_req_mod(req, QUEUE_AS_DRBD_BARRIER);
992 		return remote;
993 	}
994 
995 	if (!remote && !send_oos)
996 		return 0;
997 
998 	D_ASSERT(device, !(remote && send_oos));
999 
1000 	if (remote) {
1001 		_req_mod(req, TO_BE_SENT);
1002 		_req_mod(req, QUEUE_FOR_NET_WRITE);
1003 	} else if (drbd_set_out_of_sync(device, req->i.sector, req->i.size))
1004 		_req_mod(req, QUEUE_FOR_SEND_OOS);
1005 
1006 	return remote;
1007 }
1008 
1009 static void
1010 drbd_submit_req_private_bio(struct drbd_request *req)
1011 {
1012 	struct drbd_device *device = req->device;
1013 	struct bio *bio = req->private_bio;
1014 	const int rw = bio_rw(bio);
1015 
1016 	bio->bi_bdev = device->ldev->backing_bdev;
1017 
1018 	/* State may have changed since we grabbed our reference on the
1019 	 * ->ldev member. Double check, and short-circuit to endio.
1020 	 * In case the last activity log transaction failed to get on
1021 	 * stable storage, and this is a WRITE, we may not even submit
1022 	 * this bio. */
1023 	if (get_ldev(device)) {
1024 		if (drbd_insert_fault(device,
1025 				      rw == WRITE ? DRBD_FAULT_DT_WR
1026 				    : rw == READ  ? DRBD_FAULT_DT_RD
1027 				    :               DRBD_FAULT_DT_RA))
1028 			bio_endio(bio, -EIO);
1029 		else
1030 			generic_make_request(bio);
1031 		put_ldev(device);
1032 	} else
1033 		bio_endio(bio, -EIO);
1034 }
1035 
1036 static void drbd_queue_write(struct drbd_device *device, struct drbd_request *req)
1037 {
1038 	spin_lock(&device->submit.lock);
1039 	list_add_tail(&req->tl_requests, &device->submit.writes);
1040 	spin_unlock(&device->submit.lock);
1041 	queue_work(device->submit.wq, &device->submit.worker);
1042 }
1043 
1044 /* returns the new drbd_request pointer, if the caller is expected to
1045  * drbd_send_and_submit() it (to save latency), or NULL if we queued the
1046  * request on the submitter thread.
1047  * Returns ERR_PTR(-ENOMEM) if we cannot allocate a drbd_request.
1048  */
1049 static struct drbd_request *
1050 drbd_request_prepare(struct drbd_device *device, struct bio *bio, unsigned long start_time)
1051 {
1052 	const int rw = bio_data_dir(bio);
1053 	struct drbd_request *req;
1054 
1055 	/* allocate outside of all locks; */
1056 	req = drbd_req_new(device, bio);
1057 	if (!req) {
1058 		dec_ap_bio(device);
1059 		/* only pass the error to the upper layers.
1060 		 * if user cannot handle io errors, that's not our business. */
1061 		drbd_err(device, "could not kmalloc() req\n");
1062 		bio_endio(bio, -ENOMEM);
1063 		return ERR_PTR(-ENOMEM);
1064 	}
1065 	req->start_time = start_time;
1066 
1067 	if (!get_ldev(device)) {
1068 		bio_put(req->private_bio);
1069 		req->private_bio = NULL;
1070 	}
1071 
1072 	/* Update disk stats */
1073 	_drbd_start_io_acct(device, req);
1074 
1075 	if (rw == WRITE && req->private_bio && req->i.size
1076 	&& !test_bit(AL_SUSPENDED, &device->flags)) {
1077 		if (!drbd_al_begin_io_fastpath(device, &req->i)) {
1078 			drbd_queue_write(device, req);
1079 			return NULL;
1080 		}
1081 		req->rq_state |= RQ_IN_ACT_LOG;
1082 	}
1083 
1084 	return req;
1085 }
1086 
1087 static void drbd_send_and_submit(struct drbd_device *device, struct drbd_request *req)
1088 {
1089 	const int rw = bio_rw(req->master_bio);
1090 	struct bio_and_error m = { NULL, };
1091 	bool no_remote = false;
1092 
1093 	spin_lock_irq(&device->resource->req_lock);
1094 	if (rw == WRITE) {
1095 		/* This may temporarily give up the req_lock,
1096 		 * but will re-aquire it before it returns here.
1097 		 * Needs to be before the check on drbd_suspended() */
1098 		complete_conflicting_writes(req);
1099 		/* no more giving up req_lock from now on! */
1100 
1101 		/* check for congestion, and potentially stop sending
1102 		 * full data updates, but start sending "dirty bits" only. */
1103 		maybe_pull_ahead(device);
1104 	}
1105 
1106 
1107 	if (drbd_suspended(device)) {
1108 		/* push back and retry: */
1109 		req->rq_state |= RQ_POSTPONED;
1110 		if (req->private_bio) {
1111 			bio_put(req->private_bio);
1112 			req->private_bio = NULL;
1113 			put_ldev(device);
1114 		}
1115 		goto out;
1116 	}
1117 
1118 	/* We fail READ/READA early, if we can not serve it.
1119 	 * We must do this before req is registered on any lists.
1120 	 * Otherwise, drbd_req_complete() will queue failed READ for retry. */
1121 	if (rw != WRITE) {
1122 		if (!do_remote_read(req) && !req->private_bio)
1123 			goto nodata;
1124 	}
1125 
1126 	/* which transfer log epoch does this belong to? */
1127 	req->epoch = atomic_read(&first_peer_device(device)->connection->current_tle_nr);
1128 
1129 	/* no point in adding empty flushes to the transfer log,
1130 	 * they are mapped to drbd barriers already. */
1131 	if (likely(req->i.size!=0)) {
1132 		if (rw == WRITE)
1133 			first_peer_device(device)->connection->current_tle_writes++;
1134 
1135 		list_add_tail(&req->tl_requests, &first_peer_device(device)->connection->transfer_log);
1136 	}
1137 
1138 	if (rw == WRITE) {
1139 		if (!drbd_process_write_request(req))
1140 			no_remote = true;
1141 	} else {
1142 		/* We either have a private_bio, or we can read from remote.
1143 		 * Otherwise we had done the goto nodata above. */
1144 		if (req->private_bio == NULL) {
1145 			_req_mod(req, TO_BE_SENT);
1146 			_req_mod(req, QUEUE_FOR_NET_READ);
1147 		} else
1148 			no_remote = true;
1149 	}
1150 
1151 	if (req->private_bio) {
1152 		/* needs to be marked within the same spinlock */
1153 		_req_mod(req, TO_BE_SUBMITTED);
1154 		/* but we need to give up the spinlock to submit */
1155 		spin_unlock_irq(&device->resource->req_lock);
1156 		drbd_submit_req_private_bio(req);
1157 		spin_lock_irq(&device->resource->req_lock);
1158 	} else if (no_remote) {
1159 nodata:
1160 		if (__ratelimit(&drbd_ratelimit_state))
1161 			drbd_err(device, "IO ERROR: neither local nor remote data, sector %llu+%u\n",
1162 					(unsigned long long)req->i.sector, req->i.size >> 9);
1163 		/* A write may have been queued for send_oos, however.
1164 		 * So we can not simply free it, we must go through drbd_req_put_completion_ref() */
1165 	}
1166 
1167 out:
1168 	if (drbd_req_put_completion_ref(req, &m, 1))
1169 		kref_put(&req->kref, drbd_req_destroy);
1170 	spin_unlock_irq(&device->resource->req_lock);
1171 
1172 	if (m.bio)
1173 		complete_master_bio(device, &m);
1174 }
1175 
1176 void __drbd_make_request(struct drbd_device *device, struct bio *bio, unsigned long start_time)
1177 {
1178 	struct drbd_request *req = drbd_request_prepare(device, bio, start_time);
1179 	if (IS_ERR_OR_NULL(req))
1180 		return;
1181 	drbd_send_and_submit(device, req);
1182 }
1183 
1184 static void submit_fast_path(struct drbd_device *device, struct list_head *incoming)
1185 {
1186 	struct drbd_request *req, *tmp;
1187 	list_for_each_entry_safe(req, tmp, incoming, tl_requests) {
1188 		const int rw = bio_data_dir(req->master_bio);
1189 
1190 		if (rw == WRITE /* rw != WRITE should not even end up here! */
1191 		&& req->private_bio && req->i.size
1192 		&& !test_bit(AL_SUSPENDED, &device->flags)) {
1193 			if (!drbd_al_begin_io_fastpath(device, &req->i))
1194 				continue;
1195 
1196 			req->rq_state |= RQ_IN_ACT_LOG;
1197 		}
1198 
1199 		list_del_init(&req->tl_requests);
1200 		drbd_send_and_submit(device, req);
1201 	}
1202 }
1203 
1204 static bool prepare_al_transaction_nonblock(struct drbd_device *device,
1205 					    struct list_head *incoming,
1206 					    struct list_head *pending)
1207 {
1208 	struct drbd_request *req, *tmp;
1209 	int wake = 0;
1210 	int err;
1211 
1212 	spin_lock_irq(&device->al_lock);
1213 	list_for_each_entry_safe(req, tmp, incoming, tl_requests) {
1214 		err = drbd_al_begin_io_nonblock(device, &req->i);
1215 		if (err == -EBUSY)
1216 			wake = 1;
1217 		if (err)
1218 			continue;
1219 		req->rq_state |= RQ_IN_ACT_LOG;
1220 		list_move_tail(&req->tl_requests, pending);
1221 	}
1222 	spin_unlock_irq(&device->al_lock);
1223 	if (wake)
1224 		wake_up(&device->al_wait);
1225 
1226 	return !list_empty(pending);
1227 }
1228 
1229 void do_submit(struct work_struct *ws)
1230 {
1231 	struct drbd_device *device = container_of(ws, struct drbd_device, submit.worker);
1232 	LIST_HEAD(incoming);
1233 	LIST_HEAD(pending);
1234 	struct drbd_request *req, *tmp;
1235 
1236 	for (;;) {
1237 		spin_lock(&device->submit.lock);
1238 		list_splice_tail_init(&device->submit.writes, &incoming);
1239 		spin_unlock(&device->submit.lock);
1240 
1241 		submit_fast_path(device, &incoming);
1242 		if (list_empty(&incoming))
1243 			break;
1244 
1245 skip_fast_path:
1246 		wait_event(device->al_wait, prepare_al_transaction_nonblock(device, &incoming, &pending));
1247 		/* Maybe more was queued, while we prepared the transaction?
1248 		 * Try to stuff them into this transaction as well.
1249 		 * Be strictly non-blocking here, no wait_event, we already
1250 		 * have something to commit.
1251 		 * Stop if we don't make any more progres.
1252 		 */
1253 		for (;;) {
1254 			LIST_HEAD(more_pending);
1255 			LIST_HEAD(more_incoming);
1256 			bool made_progress;
1257 
1258 			/* It is ok to look outside the lock,
1259 			 * it's only an optimization anyways */
1260 			if (list_empty(&device->submit.writes))
1261 				break;
1262 
1263 			spin_lock(&device->submit.lock);
1264 			list_splice_tail_init(&device->submit.writes, &more_incoming);
1265 			spin_unlock(&device->submit.lock);
1266 
1267 			if (list_empty(&more_incoming))
1268 				break;
1269 
1270 			made_progress = prepare_al_transaction_nonblock(device, &more_incoming, &more_pending);
1271 
1272 			list_splice_tail_init(&more_pending, &pending);
1273 			list_splice_tail_init(&more_incoming, &incoming);
1274 
1275 			if (!made_progress)
1276 				break;
1277 		}
1278 		drbd_al_begin_io_commit(device, false);
1279 
1280 		list_for_each_entry_safe(req, tmp, &pending, tl_requests) {
1281 			list_del_init(&req->tl_requests);
1282 			drbd_send_and_submit(device, req);
1283 		}
1284 
1285 		/* If all currently hot activity log extents are kept busy by
1286 		 * incoming requests, we still must not totally starve new
1287 		 * requests to cold extents. In that case, prepare one request
1288 		 * in blocking mode. */
1289 		list_for_each_entry_safe(req, tmp, &incoming, tl_requests) {
1290 			list_del_init(&req->tl_requests);
1291 			req->rq_state |= RQ_IN_ACT_LOG;
1292 			if (!drbd_al_begin_io_prepare(device, &req->i)) {
1293 				/* Corresponding extent was hot after all? */
1294 				drbd_send_and_submit(device, req);
1295 			} else {
1296 				/* Found a request to a cold extent.
1297 				 * Put on "pending" list,
1298 				 * and try to cumulate with more. */
1299 				list_add(&req->tl_requests, &pending);
1300 				goto skip_fast_path;
1301 			}
1302 		}
1303 	}
1304 }
1305 
1306 void drbd_make_request(struct request_queue *q, struct bio *bio)
1307 {
1308 	struct drbd_device *device = (struct drbd_device *) q->queuedata;
1309 	unsigned long start_time;
1310 
1311 	start_time = jiffies;
1312 
1313 	/*
1314 	 * what we "blindly" assume:
1315 	 */
1316 	D_ASSERT(device, IS_ALIGNED(bio->bi_iter.bi_size, 512));
1317 
1318 	inc_ap_bio(device);
1319 	__drbd_make_request(device, bio, start_time);
1320 }
1321 
1322 /* This is called by bio_add_page().
1323  *
1324  * q->max_hw_sectors and other global limits are already enforced there.
1325  *
1326  * We need to call down to our lower level device,
1327  * in case it has special restrictions.
1328  *
1329  * We also may need to enforce configured max-bio-bvecs limits.
1330  *
1331  * As long as the BIO is empty we have to allow at least one bvec,
1332  * regardless of size and offset, so no need to ask lower levels.
1333  */
1334 int drbd_merge_bvec(struct request_queue *q, struct bvec_merge_data *bvm, struct bio_vec *bvec)
1335 {
1336 	struct drbd_device *device = (struct drbd_device *) q->queuedata;
1337 	unsigned int bio_size = bvm->bi_size;
1338 	int limit = DRBD_MAX_BIO_SIZE;
1339 	int backing_limit;
1340 
1341 	if (bio_size && get_ldev(device)) {
1342 		unsigned int max_hw_sectors = queue_max_hw_sectors(q);
1343 		struct request_queue * const b =
1344 			device->ldev->backing_bdev->bd_disk->queue;
1345 		if (b->merge_bvec_fn) {
1346 			backing_limit = b->merge_bvec_fn(b, bvm, bvec);
1347 			limit = min(limit, backing_limit);
1348 		}
1349 		put_ldev(device);
1350 		if ((limit >> 9) > max_hw_sectors)
1351 			limit = max_hw_sectors << 9;
1352 	}
1353 	return limit;
1354 }
1355 
1356 static void find_oldest_requests(
1357 		struct drbd_connection *connection,
1358 		struct drbd_device *device,
1359 		struct drbd_request **oldest_req_waiting_for_peer,
1360 		struct drbd_request **oldest_req_waiting_for_disk)
1361 {
1362 	struct drbd_request *r;
1363 	*oldest_req_waiting_for_peer = NULL;
1364 	*oldest_req_waiting_for_disk = NULL;
1365 	list_for_each_entry(r, &connection->transfer_log, tl_requests) {
1366 		const unsigned s = r->rq_state;
1367 		if (!*oldest_req_waiting_for_peer
1368 		&& ((s & RQ_NET_MASK) && !(s & RQ_NET_DONE)))
1369 			*oldest_req_waiting_for_peer = r;
1370 
1371 		if (!*oldest_req_waiting_for_disk
1372 		&& (s & RQ_LOCAL_PENDING) && r->device == device)
1373 			*oldest_req_waiting_for_disk = r;
1374 
1375 		if (*oldest_req_waiting_for_peer && *oldest_req_waiting_for_disk)
1376 			break;
1377 	}
1378 }
1379 
1380 void request_timer_fn(unsigned long data)
1381 {
1382 	struct drbd_device *device = (struct drbd_device *) data;
1383 	struct drbd_connection *connection = first_peer_device(device)->connection;
1384 	struct drbd_request *req_disk, *req_peer; /* oldest request */
1385 	struct net_conf *nc;
1386 	unsigned long ent = 0, dt = 0, et, nt; /* effective timeout = ko_count * timeout */
1387 	unsigned long now;
1388 
1389 	rcu_read_lock();
1390 	nc = rcu_dereference(connection->net_conf);
1391 	if (nc && device->state.conn >= C_WF_REPORT_PARAMS)
1392 		ent = nc->timeout * HZ/10 * nc->ko_count;
1393 
1394 	if (get_ldev(device)) { /* implicit state.disk >= D_INCONSISTENT */
1395 		dt = rcu_dereference(device->ldev->disk_conf)->disk_timeout * HZ / 10;
1396 		put_ldev(device);
1397 	}
1398 	rcu_read_unlock();
1399 
1400 	et = min_not_zero(dt, ent);
1401 
1402 	if (!et)
1403 		return; /* Recurring timer stopped */
1404 
1405 	now = jiffies;
1406 
1407 	spin_lock_irq(&device->resource->req_lock);
1408 	find_oldest_requests(connection, device, &req_peer, &req_disk);
1409 	if (req_peer == NULL && req_disk == NULL) {
1410 		spin_unlock_irq(&device->resource->req_lock);
1411 		mod_timer(&device->request_timer, now + et);
1412 		return;
1413 	}
1414 
1415 	/* The request is considered timed out, if
1416 	 * - we have some effective timeout from the configuration,
1417 	 *   with above state restrictions applied,
1418 	 * - the oldest request is waiting for a response from the network
1419 	 *   resp. the local disk,
1420 	 * - the oldest request is in fact older than the effective timeout,
1421 	 * - the connection was established (resp. disk was attached)
1422 	 *   for longer than the timeout already.
1423 	 * Note that for 32bit jiffies and very stable connections/disks,
1424 	 * we may have a wrap around, which is catched by
1425 	 *   !time_in_range(now, last_..._jif, last_..._jif + timeout).
1426 	 *
1427 	 * Side effect: once per 32bit wrap-around interval, which means every
1428 	 * ~198 days with 250 HZ, we have a window where the timeout would need
1429 	 * to expire twice (worst case) to become effective. Good enough.
1430 	 */
1431 	if (ent && req_peer &&
1432 		 time_after(now, req_peer->start_time + ent) &&
1433 		!time_in_range(now, connection->last_reconnect_jif, connection->last_reconnect_jif + ent)) {
1434 		drbd_warn(device, "Remote failed to finish a request within ko-count * timeout\n");
1435 		_drbd_set_state(_NS(device, conn, C_TIMEOUT), CS_VERBOSE | CS_HARD, NULL);
1436 	}
1437 	if (dt && req_disk &&
1438 		 time_after(now, req_disk->start_time + dt) &&
1439 		!time_in_range(now, device->last_reattach_jif, device->last_reattach_jif + dt)) {
1440 		drbd_warn(device, "Local backing device failed to meet the disk-timeout\n");
1441 		__drbd_chk_io_error(device, DRBD_FORCE_DETACH);
1442 	}
1443 
1444 	/* Reschedule timer for the nearest not already expired timeout.
1445 	 * Fallback to now + min(effective network timeout, disk timeout). */
1446 	ent = (ent && req_peer && time_before(now, req_peer->start_time + ent))
1447 		? req_peer->start_time + ent : now + et;
1448 	dt = (dt && req_disk && time_before(now, req_disk->start_time + dt))
1449 		? req_disk->start_time + dt : now + et;
1450 	nt = time_before(ent, dt) ? ent : dt;
1451 	spin_unlock_irq(&connection->resource->req_lock);
1452 	mod_timer(&device->request_timer, nt);
1453 }
1454