• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/components/opensource/linux/linux-2.6.36/drivers/block/drbd/
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/* Update disk stats at start of I/O request */
35static void _drbd_start_io_acct(struct drbd_conf *mdev, struct drbd_request *req, struct bio *bio)
36{
37	const int rw = bio_data_dir(bio);
38	int cpu;
39	cpu = part_stat_lock();
40	part_stat_inc(cpu, &mdev->vdisk->part0, ios[rw]);
41	part_stat_add(cpu, &mdev->vdisk->part0, sectors[rw], bio_sectors(bio));
42	part_inc_in_flight(&mdev->vdisk->part0, rw);
43	part_stat_unlock();
44}
45
46/* Update disk stats when completing request upwards */
47static void _drbd_end_io_acct(struct drbd_conf *mdev, struct drbd_request *req)
48{
49	int rw = bio_data_dir(req->master_bio);
50	unsigned long duration = jiffies - req->start_time;
51	int cpu;
52	cpu = part_stat_lock();
53	part_stat_add(cpu, &mdev->vdisk->part0, ticks[rw], duration);
54	part_round_stats(cpu, &mdev->vdisk->part0);
55	part_dec_in_flight(&mdev->vdisk->part0, rw);
56	part_stat_unlock();
57}
58
59static void _req_is_done(struct drbd_conf *mdev, struct drbd_request *req, const int rw)
60{
61	const unsigned long s = req->rq_state;
62	/* if it was a write, we may have to set the corresponding
63	 * bit(s) out-of-sync first. If it had a local part, we need to
64	 * release the reference to the activity log. */
65	if (rw == WRITE) {
66		/* remove it from the transfer log.
67		 * well, only if it had been there in the first
68		 * place... if it had not (local only or conflicting
69		 * and never sent), it should still be "empty" as
70		 * initialized in drbd_req_new(), so we can list_del() it
71		 * here unconditionally */
72		list_del(&req->tl_requests);
73		/* Set out-of-sync unless both OK flags are set
74		 * (local only or remote failed).
75		 * Other places where we set out-of-sync:
76		 * READ with local io-error */
77		if (!(s & RQ_NET_OK) || !(s & RQ_LOCAL_OK))
78			drbd_set_out_of_sync(mdev, req->sector, req->size);
79
80		if ((s & RQ_NET_OK) && (s & RQ_LOCAL_OK) && (s & RQ_NET_SIS))
81			drbd_set_in_sync(mdev, req->sector, req->size);
82
83		/* one might be tempted to move the drbd_al_complete_io
84		 * to the local io completion callback drbd_endio_pri.
85		 * but, if this was a mirror write, we may only
86		 * drbd_al_complete_io after this is RQ_NET_DONE,
87		 * otherwise the extent could be dropped from the al
88		 * before it has actually been written on the peer.
89		 * if we crash before our peer knows about the request,
90		 * but after the extent has been dropped from the al,
91		 * we would forget to resync the corresponding extent.
92		 */
93		if (s & RQ_LOCAL_MASK) {
94			if (get_ldev_if_state(mdev, D_FAILED)) {
95				drbd_al_complete_io(mdev, req->sector);
96				put_ldev(mdev);
97			} else if (__ratelimit(&drbd_ratelimit_state)) {
98				dev_warn(DEV, "Should have called drbd_al_complete_io(, %llu), "
99				     "but my Disk seems to have failed :(\n",
100				     (unsigned long long) req->sector);
101			}
102		}
103	}
104
105	drbd_req_free(req);
106}
107
108static void queue_barrier(struct drbd_conf *mdev)
109{
110	struct drbd_tl_epoch *b;
111
112	/* We are within the req_lock. Once we queued the barrier for sending,
113	 * we set the CREATE_BARRIER bit. It is cleared as soon as a new
114	 * barrier/epoch object is added. This is the only place this bit is
115	 * set. It indicates that the barrier for this epoch is already queued,
116	 * and no new epoch has been created yet. */
117	if (test_bit(CREATE_BARRIER, &mdev->flags))
118		return;
119
120	b = mdev->newest_tle;
121	b->w.cb = w_send_barrier;
122	/* inc_ap_pending done here, so we won't
123	 * get imbalanced on connection loss.
124	 * dec_ap_pending will be done in got_BarrierAck
125	 * or (on connection loss) in tl_clear.  */
126	inc_ap_pending(mdev);
127	drbd_queue_work(&mdev->data.work, &b->w);
128	set_bit(CREATE_BARRIER, &mdev->flags);
129}
130
131static void _about_to_complete_local_write(struct drbd_conf *mdev,
132	struct drbd_request *req)
133{
134	const unsigned long s = req->rq_state;
135	struct drbd_request *i;
136	struct drbd_epoch_entry *e;
137	struct hlist_node *n;
138	struct hlist_head *slot;
139
140	/* before we can signal completion to the upper layers,
141	 * we may need to close the current epoch */
142	if (mdev->state.conn >= C_CONNECTED &&
143	    req->epoch == mdev->newest_tle->br_number)
144		queue_barrier(mdev);
145
146	/* we need to do the conflict detection stuff,
147	 * if we have the ee_hash (two_primaries) and
148	 * this has been on the network */
149	if ((s & RQ_NET_DONE) && mdev->ee_hash != NULL) {
150		const sector_t sector = req->sector;
151		const int size = req->size;
152
153		/* ASSERT:
154		 * there must be no conflicting requests, since
155		 * they must have been failed on the spot */
156#define OVERLAPS overlaps(sector, size, i->sector, i->size)
157		slot = tl_hash_slot(mdev, sector);
158		hlist_for_each_entry(i, n, slot, colision) {
159			if (OVERLAPS) {
160				dev_alert(DEV, "LOGIC BUG: completed: %p %llus +%u; "
161				      "other: %p %llus +%u\n",
162				      req, (unsigned long long)sector, size,
163				      i, (unsigned long long)i->sector, i->size);
164			}
165		}
166
167		/* maybe "wake" those conflicting epoch entries
168		 * that wait for this request to finish.
169		 *
170		 * currently, there can be only _one_ such ee
171		 * (well, or some more, which would be pending
172		 * P_DISCARD_ACK not yet sent by the asender...),
173		 * since we block the receiver thread upon the
174		 * first conflict detection, which will wait on
175		 * misc_wait.  maybe we want to assert that?
176		 *
177		 * anyways, if we found one,
178		 * we just have to do a wake_up.  */
179#undef OVERLAPS
180#define OVERLAPS overlaps(sector, size, e->sector, e->size)
181		slot = ee_hash_slot(mdev, req->sector);
182		hlist_for_each_entry(e, n, slot, colision) {
183			if (OVERLAPS) {
184				wake_up(&mdev->misc_wait);
185				break;
186			}
187		}
188	}
189#undef OVERLAPS
190}
191
192void complete_master_bio(struct drbd_conf *mdev,
193		struct bio_and_error *m)
194{
195	bio_endio(m->bio, m->error);
196	dec_ap_bio(mdev);
197}
198
199/* Helper for __req_mod().
200 * Set m->bio to the master bio, if it is fit to be completed,
201 * or leave it alone (it is initialized to NULL in __req_mod),
202 * if it has already been completed, or cannot be completed yet.
203 * If m->bio is set, the error status to be returned is placed in m->error.
204 */
205void _req_may_be_done(struct drbd_request *req, struct bio_and_error *m)
206{
207	const unsigned long s = req->rq_state;
208	struct drbd_conf *mdev = req->mdev;
209	/* only WRITES may end up here without a master bio (on barrier ack) */
210	int rw = req->master_bio ? bio_data_dir(req->master_bio) : WRITE;
211
212	/* we must not complete the master bio, while it is
213	 *	still being processed by _drbd_send_zc_bio (drbd_send_dblock)
214	 *	not yet acknowledged by the peer
215	 *	not yet completed by the local io subsystem
216	 * these flags may get cleared in any order by
217	 *	the worker,
218	 *	the receiver,
219	 *	the bio_endio completion callbacks.
220	 */
221	if (s & RQ_NET_QUEUED)
222		return;
223	if (s & RQ_NET_PENDING)
224		return;
225	if (s & RQ_LOCAL_PENDING)
226		return;
227
228	if (req->master_bio) {
229		/* this is data_received (remote read)
230		 * or protocol C P_WRITE_ACK
231		 * or protocol B P_RECV_ACK
232		 * or protocol A "handed_over_to_network" (SendAck)
233		 * or canceled or failed,
234		 * or killed from the transfer log due to connection loss.
235		 */
236
237		/*
238		 * figure out whether to report success or failure.
239		 *
240		 * report success when at least one of the operations succeeded.
241		 * or, to put the other way,
242		 * only report failure, when both operations failed.
243		 *
244		 * what to do about the failures is handled elsewhere.
245		 * what we need to do here is just: complete the master_bio.
246		 *
247		 * local completion error, if any, has been stored as ERR_PTR
248		 * in private_bio within drbd_endio_pri.
249		 */
250		int ok = (s & RQ_LOCAL_OK) || (s & RQ_NET_OK);
251		int error = PTR_ERR(req->private_bio);
252
253		/* remove the request from the conflict detection
254		 * respective block_id verification hash */
255		if (!hlist_unhashed(&req->colision))
256			hlist_del(&req->colision);
257		else
258			D_ASSERT((s & RQ_NET_MASK) == 0);
259
260		/* for writes we need to do some extra housekeeping */
261		if (rw == WRITE)
262			_about_to_complete_local_write(mdev, req);
263
264		/* Update disk stats */
265		_drbd_end_io_acct(mdev, req);
266
267		m->error = ok ? 0 : (error ?: -EIO);
268		m->bio = req->master_bio;
269		req->master_bio = NULL;
270	}
271
272	if ((s & RQ_NET_MASK) == 0 || (s & RQ_NET_DONE)) {
273		/* this is disconnected (local only) operation,
274		 * or protocol C P_WRITE_ACK,
275		 * or protocol A or B P_BARRIER_ACK,
276		 * or killed from the transfer log due to connection loss. */
277		_req_is_done(mdev, req, rw);
278	}
279	/* else: network part and not DONE yet. that is
280	 * protocol A or B, barrier ack still pending... */
281}
282
283/*
284 * checks whether there was an overlapping request
285 * or ee already registered.
286 *
287 * if so, return 1, in which case this request is completed on the spot,
288 * without ever being submitted or send.
289 *
290 * return 0 if it is ok to submit this request.
291 *
292 * NOTE:
293 * paranoia: assume something above us is broken, and issues different write
294 * requests for the same block simultaneously...
295 *
296 * To ensure these won't be reordered differently on both nodes, resulting in
297 * diverging data sets, we discard the later one(s). Not that this is supposed
298 * to happen, but this is the rationale why we also have to check for
299 * conflicting requests with local origin, and why we have to do so regardless
300 * of whether we allowed multiple primaries.
301 *
302 * BTW, in case we only have one primary, the ee_hash is empty anyways, and the
303 * second hlist_for_each_entry becomes a noop. This is even simpler than to
304 * grab a reference on the net_conf, and check for the two_primaries flag...
305 */
306static int _req_conflicts(struct drbd_request *req)
307{
308	struct drbd_conf *mdev = req->mdev;
309	const sector_t sector = req->sector;
310	const int size = req->size;
311	struct drbd_request *i;
312	struct drbd_epoch_entry *e;
313	struct hlist_node *n;
314	struct hlist_head *slot;
315
316	D_ASSERT(hlist_unhashed(&req->colision));
317
318	if (!get_net_conf(mdev))
319		return 0;
320
321	/* BUG_ON */
322	ERR_IF (mdev->tl_hash_s == 0)
323		goto out_no_conflict;
324	BUG_ON(mdev->tl_hash == NULL);
325
326#define OVERLAPS overlaps(i->sector, i->size, sector, size)
327	slot = tl_hash_slot(mdev, sector);
328	hlist_for_each_entry(i, n, slot, colision) {
329		if (OVERLAPS) {
330			dev_alert(DEV, "%s[%u] Concurrent local write detected! "
331			      "[DISCARD L] new: %llus +%u; "
332			      "pending: %llus +%u\n",
333			      current->comm, current->pid,
334			      (unsigned long long)sector, size,
335			      (unsigned long long)i->sector, i->size);
336			goto out_conflict;
337		}
338	}
339
340	if (mdev->ee_hash_s) {
341		/* now, check for overlapping requests with remote origin */
342		BUG_ON(mdev->ee_hash == NULL);
343#undef OVERLAPS
344#define OVERLAPS overlaps(e->sector, e->size, sector, size)
345		slot = ee_hash_slot(mdev, sector);
346		hlist_for_each_entry(e, n, slot, colision) {
347			if (OVERLAPS) {
348				dev_alert(DEV, "%s[%u] Concurrent remote write detected!"
349				      " [DISCARD L] new: %llus +%u; "
350				      "pending: %llus +%u\n",
351				      current->comm, current->pid,
352				      (unsigned long long)sector, size,
353				      (unsigned long long)e->sector, e->size);
354				goto out_conflict;
355			}
356		}
357	}
358#undef OVERLAPS
359
360out_no_conflict:
361	/* this is like it should be, and what we expected.
362	 * our users do behave after all... */
363	put_net_conf(mdev);
364	return 0;
365
366out_conflict:
367	put_net_conf(mdev);
368	return 1;
369}
370
371/* obviously this could be coded as many single functions
372 * instead of one huge switch,
373 * or by putting the code directly in the respective locations
374 * (as it has been before).
375 *
376 * but having it this way
377 *  enforces that it is all in this one place, where it is easier to audit,
378 *  it makes it obvious that whatever "event" "happens" to a request should
379 *  happen "atomically" within the req_lock,
380 *  and it enforces that we have to think in a very structured manner
381 *  about the "events" that may happen to a request during its life time ...
382 */
383void __req_mod(struct drbd_request *req, enum drbd_req_event what,
384		struct bio_and_error *m)
385{
386	struct drbd_conf *mdev = req->mdev;
387	m->bio = NULL;
388
389	switch (what) {
390	default:
391		dev_err(DEV, "LOGIC BUG in %s:%u\n", __FILE__ , __LINE__);
392		break;
393
394	/* does not happen...
395	 * initialization done in drbd_req_new
396	case created:
397		break;
398		*/
399
400	case to_be_send: /* via network */
401		/* reached via drbd_make_request_common
402		 * and from w_read_retry_remote */
403		D_ASSERT(!(req->rq_state & RQ_NET_MASK));
404		req->rq_state |= RQ_NET_PENDING;
405		inc_ap_pending(mdev);
406		break;
407
408	case to_be_submitted: /* locally */
409		/* reached via drbd_make_request_common */
410		D_ASSERT(!(req->rq_state & RQ_LOCAL_MASK));
411		req->rq_state |= RQ_LOCAL_PENDING;
412		break;
413
414	case completed_ok:
415		if (bio_data_dir(req->master_bio) == WRITE)
416			mdev->writ_cnt += req->size>>9;
417		else
418			mdev->read_cnt += req->size>>9;
419
420		req->rq_state |= (RQ_LOCAL_COMPLETED|RQ_LOCAL_OK);
421		req->rq_state &= ~RQ_LOCAL_PENDING;
422
423		_req_may_be_done(req, m);
424		put_ldev(mdev);
425		break;
426
427	case write_completed_with_error:
428		req->rq_state |= RQ_LOCAL_COMPLETED;
429		req->rq_state &= ~RQ_LOCAL_PENDING;
430
431		__drbd_chk_io_error(mdev, FALSE);
432		_req_may_be_done(req, m);
433		put_ldev(mdev);
434		break;
435
436	case read_ahead_completed_with_error:
437		/* it is legal to fail READA */
438		req->rq_state |= RQ_LOCAL_COMPLETED;
439		req->rq_state &= ~RQ_LOCAL_PENDING;
440		_req_may_be_done(req, m);
441		put_ldev(mdev);
442		break;
443
444	case read_completed_with_error:
445		drbd_set_out_of_sync(mdev, req->sector, req->size);
446
447		req->rq_state |= RQ_LOCAL_COMPLETED;
448		req->rq_state &= ~RQ_LOCAL_PENDING;
449
450		D_ASSERT(!(req->rq_state & RQ_NET_MASK));
451
452		__drbd_chk_io_error(mdev, FALSE);
453		put_ldev(mdev);
454
455		/* no point in retrying if there is no good remote data,
456		 * or we have no connection. */
457		if (mdev->state.pdsk != D_UP_TO_DATE) {
458			_req_may_be_done(req, m);
459			break;
460		}
461
462		/* _req_mod(req,to_be_send); oops, recursion... */
463		req->rq_state |= RQ_NET_PENDING;
464		inc_ap_pending(mdev);
465		/* fall through: _req_mod(req,queue_for_net_read); */
466
467	case queue_for_net_read:
468		/* READ or READA, and
469		 * no local disk,
470		 * or target area marked as invalid,
471		 * or just got an io-error. */
472		/* from drbd_make_request_common
473		 * or from bio_endio during read io-error recovery */
474
475		/* so we can verify the handle in the answer packet
476		 * corresponding hlist_del is in _req_may_be_done() */
477		hlist_add_head(&req->colision, ar_hash_slot(mdev, req->sector));
478
479		set_bit(UNPLUG_REMOTE, &mdev->flags);
480
481		D_ASSERT(req->rq_state & RQ_NET_PENDING);
482		req->rq_state |= RQ_NET_QUEUED;
483		req->w.cb = (req->rq_state & RQ_LOCAL_MASK)
484			? w_read_retry_remote
485			: w_send_read_req;
486		drbd_queue_work(&mdev->data.work, &req->w);
487		break;
488
489	case queue_for_net_write:
490		/* assert something? */
491		/* from drbd_make_request_common only */
492
493		hlist_add_head(&req->colision, tl_hash_slot(mdev, req->sector));
494		/* corresponding hlist_del is in _req_may_be_done() */
495
496		/* NOTE
497		 * In case the req ended up on the transfer log before being
498		 * queued on the worker, it could lead to this request being
499		 * missed during cleanup after connection loss.
500		 * So we have to do both operations here,
501		 * within the same lock that protects the transfer log.
502		 *
503		 * _req_add_to_epoch(req); this has to be after the
504		 * _maybe_start_new_epoch(req); which happened in
505		 * drbd_make_request_common, because we now may set the bit
506		 * again ourselves to close the current epoch.
507		 *
508		 * Add req to the (now) current epoch (barrier). */
509
510		/* otherwise we may lose an unplug, which may cause some remote
511		 * io-scheduler timeout to expire, increasing maximum latency,
512		 * hurting performance. */
513		set_bit(UNPLUG_REMOTE, &mdev->flags);
514
515		/* see drbd_make_request_common,
516		 * just after it grabs the req_lock */
517		D_ASSERT(test_bit(CREATE_BARRIER, &mdev->flags) == 0);
518
519		req->epoch = mdev->newest_tle->br_number;
520		list_add_tail(&req->tl_requests,
521				&mdev->newest_tle->requests);
522
523		/* increment size of current epoch */
524		mdev->newest_tle->n_req++;
525
526		/* queue work item to send data */
527		D_ASSERT(req->rq_state & RQ_NET_PENDING);
528		req->rq_state |= RQ_NET_QUEUED;
529		req->w.cb =  w_send_dblock;
530		drbd_queue_work(&mdev->data.work, &req->w);
531
532		/* close the epoch, in case it outgrew the limit */
533		if (mdev->newest_tle->n_req >= mdev->net_conf->max_epoch_size)
534			queue_barrier(mdev);
535
536		break;
537
538	case send_canceled:
539		/* treat it the same */
540	case send_failed:
541		/* real cleanup will be done from tl_clear.  just update flags
542		 * so it is no longer marked as on the worker queue */
543		req->rq_state &= ~RQ_NET_QUEUED;
544		/* if we did it right, tl_clear should be scheduled only after
545		 * this, so this should not be necessary! */
546		_req_may_be_done(req, m);
547		break;
548
549	case handed_over_to_network:
550		/* assert something? */
551		if (bio_data_dir(req->master_bio) == WRITE &&
552		    mdev->net_conf->wire_protocol == DRBD_PROT_A) {
553			/* this is what is dangerous about protocol A:
554			 * pretend it was successfully written on the peer. */
555			if (req->rq_state & RQ_NET_PENDING) {
556				dec_ap_pending(mdev);
557				req->rq_state &= ~RQ_NET_PENDING;
558				req->rq_state |= RQ_NET_OK;
559			} /* else: neg-ack was faster... */
560			/* it is still not yet RQ_NET_DONE until the
561			 * corresponding epoch barrier got acked as well,
562			 * so we know what to dirty on connection loss */
563		}
564		req->rq_state &= ~RQ_NET_QUEUED;
565		req->rq_state |= RQ_NET_SENT;
566		/* because _drbd_send_zc_bio could sleep, and may want to
567		 * dereference the bio even after the "write_acked_by_peer" and
568		 * "completed_ok" events came in, once we return from
569		 * _drbd_send_zc_bio (drbd_send_dblock), we have to check
570		 * whether it is done already, and end it.  */
571		_req_may_be_done(req, m);
572		break;
573
574	case read_retry_remote_canceled:
575		req->rq_state &= ~RQ_NET_QUEUED;
576		/* fall through, in case we raced with drbd_disconnect */
577	case connection_lost_while_pending:
578		/* transfer log cleanup after connection loss */
579		/* assert something? */
580		if (req->rq_state & RQ_NET_PENDING)
581			dec_ap_pending(mdev);
582		req->rq_state &= ~(RQ_NET_OK|RQ_NET_PENDING);
583		req->rq_state |= RQ_NET_DONE;
584		/* if it is still queued, we may not complete it here.
585		 * it will be canceled soon. */
586		if (!(req->rq_state & RQ_NET_QUEUED))
587			_req_may_be_done(req, m);
588		break;
589
590	case write_acked_by_peer_and_sis:
591		req->rq_state |= RQ_NET_SIS;
592	case conflict_discarded_by_peer:
593		/* for discarded conflicting writes of multiple primaries,
594		 * there is no need to keep anything in the tl, potential
595		 * node crashes are covered by the activity log. */
596		if (what == conflict_discarded_by_peer)
597			dev_alert(DEV, "Got DiscardAck packet %llus +%u!"
598			      " DRBD is not a random data generator!\n",
599			      (unsigned long long)req->sector, req->size);
600		req->rq_state |= RQ_NET_DONE;
601		/* fall through */
602	case write_acked_by_peer:
603		/* protocol C; successfully written on peer.
604		 * Nothing to do here.
605		 * We want to keep the tl in place for all protocols, to cater
606		 * for volatile write-back caches on lower level devices.
607		 *
608		 * A barrier request is expected to have forced all prior
609		 * requests onto stable storage, so completion of a barrier
610		 * request could set NET_DONE right here, and not wait for the
611		 * P_BARRIER_ACK, but that is an unnecessary optimization. */
612
613		/* this makes it effectively the same as for: */
614	case recv_acked_by_peer:
615		/* protocol B; pretends to be successfully written on peer.
616		 * see also notes above in handed_over_to_network about
617		 * protocol != C */
618		req->rq_state |= RQ_NET_OK;
619		D_ASSERT(req->rq_state & RQ_NET_PENDING);
620		dec_ap_pending(mdev);
621		req->rq_state &= ~RQ_NET_PENDING;
622		_req_may_be_done(req, m);
623		break;
624
625	case neg_acked:
626		/* assert something? */
627		if (req->rq_state & RQ_NET_PENDING)
628			dec_ap_pending(mdev);
629		req->rq_state &= ~(RQ_NET_OK|RQ_NET_PENDING);
630
631		req->rq_state |= RQ_NET_DONE;
632		_req_may_be_done(req, m);
633		/* else: done by handed_over_to_network */
634		break;
635
636	case barrier_acked:
637		if (req->rq_state & RQ_NET_PENDING) {
638			/* barrier came in before all requests have been acked.
639			 * this is bad, because if the connection is lost now,
640			 * we won't be able to clean them up... */
641			dev_err(DEV, "FIXME (barrier_acked but pending)\n");
642			list_move(&req->tl_requests, &mdev->out_of_sequence_requests);
643		}
644		D_ASSERT(req->rq_state & RQ_NET_SENT);
645		req->rq_state |= RQ_NET_DONE;
646		_req_may_be_done(req, m);
647		break;
648
649	case data_received:
650		D_ASSERT(req->rq_state & RQ_NET_PENDING);
651		dec_ap_pending(mdev);
652		req->rq_state &= ~RQ_NET_PENDING;
653		req->rq_state |= (RQ_NET_OK|RQ_NET_DONE);
654		_req_may_be_done(req, m);
655		break;
656	};
657}
658
659/* we may do a local read if:
660 * - we are consistent (of course),
661 * - or we are generally inconsistent,
662 *   BUT we are still/already IN SYNC for this area.
663 *   since size may be bigger than BM_BLOCK_SIZE,
664 *   we may need to check several bits.
665 */
666static int drbd_may_do_local_read(struct drbd_conf *mdev, sector_t sector, int size)
667{
668	unsigned long sbnr, ebnr;
669	sector_t esector, nr_sectors;
670
671	if (mdev->state.disk == D_UP_TO_DATE)
672		return 1;
673	if (mdev->state.disk >= D_OUTDATED)
674		return 0;
675	if (mdev->state.disk <  D_INCONSISTENT)
676		return 0;
677	/* state.disk == D_INCONSISTENT   We will have a look at the BitMap */
678	nr_sectors = drbd_get_capacity(mdev->this_bdev);
679	esector = sector + (size >> 9) - 1;
680
681	D_ASSERT(sector  < nr_sectors);
682	D_ASSERT(esector < nr_sectors);
683
684	sbnr = BM_SECT_TO_BIT(sector);
685	ebnr = BM_SECT_TO_BIT(esector);
686
687	return 0 == drbd_bm_count_bits(mdev, sbnr, ebnr);
688}
689
690static int drbd_make_request_common(struct drbd_conf *mdev, struct bio *bio)
691{
692	const int rw = bio_rw(bio);
693	const int size = bio->bi_size;
694	const sector_t sector = bio->bi_sector;
695	struct drbd_tl_epoch *b = NULL;
696	struct drbd_request *req;
697	int local, remote;
698	int err = -EIO;
699	int ret = 0;
700
701	/* allocate outside of all locks; */
702	req = drbd_req_new(mdev, bio);
703	if (!req) {
704		dec_ap_bio(mdev);
705		/* only pass the error to the upper layers.
706		 * if user cannot handle io errors, that's not our business. */
707		dev_err(DEV, "could not kmalloc() req\n");
708		bio_endio(bio, -ENOMEM);
709		return 0;
710	}
711
712	local = get_ldev(mdev);
713	if (!local) {
714		bio_put(req->private_bio); /* or we get a bio leak */
715		req->private_bio = NULL;
716	}
717	if (rw == WRITE) {
718		remote = 1;
719	} else {
720		/* READ || READA */
721		if (local) {
722			if (!drbd_may_do_local_read(mdev, sector, size)) {
723				/* we could kick the syncer to
724				 * sync this extent asap, wait for
725				 * it, then continue locally.
726				 * Or just issue the request remotely.
727				 */
728				local = 0;
729				bio_put(req->private_bio);
730				req->private_bio = NULL;
731				put_ldev(mdev);
732			}
733		}
734		remote = !local && mdev->state.pdsk >= D_UP_TO_DATE;
735	}
736
737	/* If we have a disk, but a READA request is mapped to remote,
738	 * we are R_PRIMARY, D_INCONSISTENT, SyncTarget.
739	 * Just fail that READA request right here.
740	 *
741	 * THINK: maybe fail all READA when not local?
742	 *        or make this configurable...
743	 *        if network is slow, READA won't do any good.
744	 */
745	if (rw == READA && mdev->state.disk >= D_INCONSISTENT && !local) {
746		err = -EWOULDBLOCK;
747		goto fail_and_free_req;
748	}
749
750	/* For WRITES going to the local disk, grab a reference on the target
751	 * extent.  This waits for any resync activity in the corresponding
752	 * resync extent to finish, and, if necessary, pulls in the target
753	 * extent into the activity log, which involves further disk io because
754	 * of transactional on-disk meta data updates. */
755	if (rw == WRITE && local)
756		drbd_al_begin_io(mdev, sector);
757
758	remote = remote && (mdev->state.pdsk == D_UP_TO_DATE ||
759			    (mdev->state.pdsk == D_INCONSISTENT &&
760			     mdev->state.conn >= C_CONNECTED));
761
762	if (!(local || remote) && !mdev->state.susp) {
763		dev_err(DEV, "IO ERROR: neither local nor remote disk\n");
764		goto fail_free_complete;
765	}
766
767	/* For WRITE request, we have to make sure that we have an
768	 * unused_spare_tle, in case we need to start a new epoch.
769	 * I try to be smart and avoid to pre-allocate always "just in case",
770	 * but there is a race between testing the bit and pointer outside the
771	 * spinlock, and grabbing the spinlock.
772	 * if we lost that race, we retry.  */
773	if (rw == WRITE && remote &&
774	    mdev->unused_spare_tle == NULL &&
775	    test_bit(CREATE_BARRIER, &mdev->flags)) {
776allocate_barrier:
777		b = kmalloc(sizeof(struct drbd_tl_epoch), GFP_NOIO);
778		if (!b) {
779			dev_err(DEV, "Failed to alloc barrier.\n");
780			err = -ENOMEM;
781			goto fail_free_complete;
782		}
783	}
784
785	/* GOOD, everything prepared, grab the spin_lock */
786	spin_lock_irq(&mdev->req_lock);
787
788	if (mdev->state.susp) {
789		/* If we got suspended, use the retry mechanism of
790		   generic_make_request() to restart processing of this
791		   bio. In the next call to drbd_make_request_26
792		   we sleep in inc_ap_bio() */
793		ret = 1;
794		spin_unlock_irq(&mdev->req_lock);
795		goto fail_free_complete;
796	}
797
798	if (remote) {
799		remote = (mdev->state.pdsk == D_UP_TO_DATE ||
800			    (mdev->state.pdsk == D_INCONSISTENT &&
801			     mdev->state.conn >= C_CONNECTED));
802		if (!remote)
803			dev_warn(DEV, "lost connection while grabbing the req_lock!\n");
804		if (!(local || remote)) {
805			dev_err(DEV, "IO ERROR: neither local nor remote disk\n");
806			spin_unlock_irq(&mdev->req_lock);
807			goto fail_free_complete;
808		}
809	}
810
811	if (b && mdev->unused_spare_tle == NULL) {
812		mdev->unused_spare_tle = b;
813		b = NULL;
814	}
815	if (rw == WRITE && remote &&
816	    mdev->unused_spare_tle == NULL &&
817	    test_bit(CREATE_BARRIER, &mdev->flags)) {
818		/* someone closed the current epoch
819		 * while we were grabbing the spinlock */
820		spin_unlock_irq(&mdev->req_lock);
821		goto allocate_barrier;
822	}
823
824
825	/* Update disk stats */
826	_drbd_start_io_acct(mdev, req, bio);
827
828	/* _maybe_start_new_epoch(mdev);
829	 * If we need to generate a write barrier packet, we have to add the
830	 * new epoch (barrier) object, and queue the barrier packet for sending,
831	 * and queue the req's data after it _within the same lock_, otherwise
832	 * we have race conditions were the reorder domains could be mixed up.
833	 *
834	 * Even read requests may start a new epoch and queue the corresponding
835	 * barrier packet.  To get the write ordering right, we only have to
836	 * make sure that, if this is a write request and it triggered a
837	 * barrier packet, this request is queued within the same spinlock. */
838	if (remote && mdev->unused_spare_tle &&
839	    test_and_clear_bit(CREATE_BARRIER, &mdev->flags)) {
840		_tl_add_barrier(mdev, mdev->unused_spare_tle);
841		mdev->unused_spare_tle = NULL;
842	} else {
843		D_ASSERT(!(remote && rw == WRITE &&
844			   test_bit(CREATE_BARRIER, &mdev->flags)));
845	}
846
847	/* NOTE
848	 * Actually, 'local' may be wrong here already, since we may have failed
849	 * to write to the meta data, and may become wrong anytime because of
850	 * local io-error for some other request, which would lead to us
851	 * "detaching" the local disk.
852	 *
853	 * 'remote' may become wrong any time because the network could fail.
854	 *
855	 * This is a harmless race condition, though, since it is handled
856	 * correctly at the appropriate places; so it just defers the failure
857	 * of the respective operation.
858	 */
859
860	/* mark them early for readability.
861	 * this just sets some state flags. */
862	if (remote)
863		_req_mod(req, to_be_send);
864	if (local)
865		_req_mod(req, to_be_submitted);
866
867	/* check this request on the collision detection hash tables.
868	 * if we have a conflict, just complete it here.
869	 * THINK do we want to check reads, too? (I don't think so...) */
870	if (rw == WRITE && _req_conflicts(req)) {
871		/* this is a conflicting request.
872		 * even though it may have been only _partially_
873		 * overlapping with one of the currently pending requests,
874		 * without even submitting or sending it, we will
875		 * pretend that it was successfully served right now.
876		 */
877		if (local) {
878			bio_put(req->private_bio);
879			req->private_bio = NULL;
880			drbd_al_complete_io(mdev, req->sector);
881			put_ldev(mdev);
882			local = 0;
883		}
884		if (remote)
885			dec_ap_pending(mdev);
886		_drbd_end_io_acct(mdev, req);
887		/* THINK: do we want to fail it (-EIO), or pretend success? */
888		bio_endio(req->master_bio, 0);
889		req->master_bio = NULL;
890		dec_ap_bio(mdev);
891		drbd_req_free(req);
892		remote = 0;
893	}
894
895	/* NOTE remote first: to get the concurrent write detection right,
896	 * we must register the request before start of local IO.  */
897	if (remote) {
898		/* either WRITE and C_CONNECTED,
899		 * or READ, and no local disk,
900		 * or READ, but not in sync.
901		 */
902		_req_mod(req, (rw == WRITE)
903				? queue_for_net_write
904				: queue_for_net_read);
905	}
906	spin_unlock_irq(&mdev->req_lock);
907	kfree(b); /* if someone else has beaten us to it... */
908
909	if (local) {
910		req->private_bio->bi_bdev = mdev->ldev->backing_bdev;
911
912		if (FAULT_ACTIVE(mdev, rw == WRITE ? DRBD_FAULT_DT_WR
913				     : rw == READ  ? DRBD_FAULT_DT_RD
914				     :               DRBD_FAULT_DT_RA))
915			bio_endio(req->private_bio, -EIO);
916		else
917			generic_make_request(req->private_bio);
918	}
919
920	/* we need to plug ALWAYS since we possibly need to kick lo_dev.
921	 * we plug after submit, so we won't miss an unplug event */
922	drbd_plug_device(mdev);
923
924	return 0;
925
926fail_free_complete:
927	if (rw == WRITE && local)
928		drbd_al_complete_io(mdev, sector);
929fail_and_free_req:
930	if (local) {
931		bio_put(req->private_bio);
932		req->private_bio = NULL;
933		put_ldev(mdev);
934	}
935	if (!ret)
936		bio_endio(bio, err);
937
938	drbd_req_free(req);
939	dec_ap_bio(mdev);
940	kfree(b);
941
942	return ret;
943}
944
945/* helper function for drbd_make_request
946 * if we can determine just by the mdev (state) that this request will fail,
947 * return 1
948 * otherwise return 0
949 */
950static int drbd_fail_request_early(struct drbd_conf *mdev, int is_write)
951{
952	if (mdev->state.role != R_PRIMARY &&
953		(!allow_oos || is_write)) {
954		if (__ratelimit(&drbd_ratelimit_state)) {
955			dev_err(DEV, "Process %s[%u] tried to %s; "
956			    "since we are not in Primary state, "
957			    "we cannot allow this\n",
958			    current->comm, current->pid,
959			    is_write ? "WRITE" : "READ");
960		}
961		return 1;
962	}
963
964	/*
965	 * Paranoia: we might have been primary, but sync target, or
966	 * even diskless, then lost the connection.
967	 * This should have been handled (panic? suspend?) somewhere
968	 * else. But maybe it was not, so check again here.
969	 * Caution: as long as we do not have a read/write lock on mdev,
970	 * to serialize state changes, this is racy, since we may lose
971	 * the connection *after* we test for the cstate.
972	 */
973	if (mdev->state.disk < D_UP_TO_DATE && mdev->state.pdsk < D_UP_TO_DATE) {
974		if (__ratelimit(&drbd_ratelimit_state))
975			dev_err(DEV, "Sorry, I have no access to good data anymore.\n");
976		return 1;
977	}
978
979	return 0;
980}
981
982int drbd_make_request_26(struct request_queue *q, struct bio *bio)
983{
984	unsigned int s_enr, e_enr;
985	struct drbd_conf *mdev = (struct drbd_conf *) q->queuedata;
986
987	if (drbd_fail_request_early(mdev, bio_data_dir(bio) & WRITE)) {
988		bio_endio(bio, -EPERM);
989		return 0;
990	}
991
992	if (unlikely(bio->bi_rw & REQ_HARDBARRIER) && test_bit(NO_BARRIER_SUPP, &mdev->flags)) {
993		/* dev_warn(DEV, "Rejecting barrier request as underlying device does not support\n"); */
994		bio_endio(bio, -EOPNOTSUPP);
995		return 0;
996	}
997
998	/*
999	 * what we "blindly" assume:
1000	 */
1001	D_ASSERT(bio->bi_size > 0);
1002	D_ASSERT((bio->bi_size & 0x1ff) == 0);
1003	D_ASSERT(bio->bi_idx == 0);
1004
1005	/* to make some things easier, force alignment of requests within the
1006	 * granularity of our hash tables */
1007	s_enr = bio->bi_sector >> HT_SHIFT;
1008	e_enr = (bio->bi_sector+(bio->bi_size>>9)-1) >> HT_SHIFT;
1009
1010	if (likely(s_enr == e_enr)) {
1011		inc_ap_bio(mdev, 1);
1012		return drbd_make_request_common(mdev, bio);
1013	}
1014
1015	/* can this bio be split generically?
1016	 * Maybe add our own split-arbitrary-bios function. */
1017	if (bio->bi_vcnt != 1 || bio->bi_idx != 0 || bio->bi_size > DRBD_MAX_SEGMENT_SIZE) {
1018		/* rather error out here than BUG in bio_split */
1019		dev_err(DEV, "bio would need to, but cannot, be split: "
1020		    "(vcnt=%u,idx=%u,size=%u,sector=%llu)\n",
1021		    bio->bi_vcnt, bio->bi_idx, bio->bi_size,
1022		    (unsigned long long)bio->bi_sector);
1023		bio_endio(bio, -EINVAL);
1024	} else {
1025		/* This bio crosses some boundary, so we have to split it. */
1026		struct bio_pair *bp;
1027		/* works for the "do not cross hash slot boundaries" case
1028		 * e.g. sector 262269, size 4096
1029		 * s_enr = 262269 >> 6 = 4097
1030		 * e_enr = (262269+8-1) >> 6 = 4098
1031		 * HT_SHIFT = 6
1032		 * sps = 64, mask = 63
1033		 * first_sectors = 64 - (262269 & 63) = 3
1034		 */
1035		const sector_t sect = bio->bi_sector;
1036		const int sps = 1 << HT_SHIFT; /* sectors per slot */
1037		const int mask = sps - 1;
1038		const sector_t first_sectors = sps - (sect & mask);
1039		bp = bio_split(bio,
1040#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,28)
1041				bio_split_pool,
1042#endif
1043				first_sectors);
1044
1045		/* we need to get a "reference count" (ap_bio_cnt)
1046		 * to avoid races with the disconnect/reconnect/suspend code.
1047		 * In case we need to split the bio here, we need to get three references
1048		 * atomically, otherwise we might deadlock when trying to submit the
1049		 * second one! */
1050		inc_ap_bio(mdev, 3);
1051
1052		D_ASSERT(e_enr == s_enr + 1);
1053
1054		while (drbd_make_request_common(mdev, &bp->bio1))
1055			inc_ap_bio(mdev, 1);
1056
1057		while (drbd_make_request_common(mdev, &bp->bio2))
1058			inc_ap_bio(mdev, 1);
1059
1060		dec_ap_bio(mdev);
1061
1062		bio_pair_release(bp);
1063	}
1064	return 0;
1065}
1066
1067/* This is called by bio_add_page().  With this function we reduce
1068 * the number of BIOs that span over multiple DRBD_MAX_SEGMENT_SIZEs
1069 * units (was AL_EXTENTs).
1070 *
1071 * we do the calculation within the lower 32bit of the byte offsets,
1072 * since we don't care for actual offset, but only check whether it
1073 * would cross "activity log extent" boundaries.
1074 *
1075 * As long as the BIO is empty we have to allow at least one bvec,
1076 * regardless of size and offset.  so the resulting bio may still
1077 * cross extent boundaries.  those are dealt with (bio_split) in
1078 * drbd_make_request_26.
1079 */
1080int drbd_merge_bvec(struct request_queue *q, struct bvec_merge_data *bvm, struct bio_vec *bvec)
1081{
1082	struct drbd_conf *mdev = (struct drbd_conf *) q->queuedata;
1083	unsigned int bio_offset =
1084		(unsigned int)bvm->bi_sector << 9; /* 32 bit */
1085	unsigned int bio_size = bvm->bi_size;
1086	int limit, backing_limit;
1087
1088	limit = DRBD_MAX_SEGMENT_SIZE
1089	      - ((bio_offset & (DRBD_MAX_SEGMENT_SIZE-1)) + bio_size);
1090	if (limit < 0)
1091		limit = 0;
1092	if (bio_size == 0) {
1093		if (limit <= bvec->bv_len)
1094			limit = bvec->bv_len;
1095	} else if (limit && get_ldev(mdev)) {
1096		struct request_queue * const b =
1097			mdev->ldev->backing_bdev->bd_disk->queue;
1098		if (b->merge_bvec_fn) {
1099			backing_limit = b->merge_bvec_fn(b, bvm, bvec);
1100			limit = min(limit, backing_limit);
1101		}
1102		put_ldev(mdev);
1103	}
1104	return limit;
1105}
1106