8915644af722cb0620a474816ec14d00885427d7
[safe/jmp/linux-2.6] / drivers / block / drbd / drbd_req.c
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 */
35 static 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 */
47 static 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
59 static 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
108 static 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
131 static 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
192 void 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  */
205 void _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  */
306 static 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
360 out_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
366 out_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  */
383 void __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                 dev_alert(DEV, "Local WRITE failed sec=%llus size=%u\n",
432                       (unsigned long long)req->sector, req->size);
433                 /* and now: check how to handle local io error. */
434                 __drbd_chk_io_error(mdev, FALSE);
435                 _req_may_be_done(req, m);
436                 put_ldev(mdev);
437                 break;
438
439         case read_ahead_completed_with_error:
440                 /* it is legal to fail READA */
441                 req->rq_state |= RQ_LOCAL_COMPLETED;
442                 req->rq_state &= ~RQ_LOCAL_PENDING;
443                 _req_may_be_done(req, m);
444                 put_ldev(mdev);
445                 break;
446
447         case read_completed_with_error:
448                 drbd_set_out_of_sync(mdev, req->sector, req->size);
449
450                 req->rq_state |= RQ_LOCAL_COMPLETED;
451                 req->rq_state &= ~RQ_LOCAL_PENDING;
452
453                 dev_alert(DEV, "Local READ failed sec=%llus size=%u\n",
454                       (unsigned long long)req->sector, req->size);
455                 D_ASSERT(!(req->rq_state & RQ_NET_MASK));
456
457                 __drbd_chk_io_error(mdev, FALSE);
458                 put_ldev(mdev);
459
460                 /* no point in retrying if there is no good remote data,
461                  * or we have no connection. */
462                 if (mdev->state.pdsk != D_UP_TO_DATE) {
463                         _req_may_be_done(req, m);
464                         break;
465                 }
466
467                 /* _req_mod(req,to_be_send); oops, recursion... */
468                 req->rq_state |= RQ_NET_PENDING;
469                 inc_ap_pending(mdev);
470                 /* fall through: _req_mod(req,queue_for_net_read); */
471
472         case queue_for_net_read:
473                 /* READ or READA, and
474                  * no local disk,
475                  * or target area marked as invalid,
476                  * or just got an io-error. */
477                 /* from drbd_make_request_common
478                  * or from bio_endio during read io-error recovery */
479
480                 /* so we can verify the handle in the answer packet
481                  * corresponding hlist_del is in _req_may_be_done() */
482                 hlist_add_head(&req->colision, ar_hash_slot(mdev, req->sector));
483
484                 set_bit(UNPLUG_REMOTE, &mdev->flags);
485
486                 D_ASSERT(req->rq_state & RQ_NET_PENDING);
487                 req->rq_state |= RQ_NET_QUEUED;
488                 req->w.cb = (req->rq_state & RQ_LOCAL_MASK)
489                         ? w_read_retry_remote
490                         : w_send_read_req;
491                 drbd_queue_work(&mdev->data.work, &req->w);
492                 break;
493
494         case queue_for_net_write:
495                 /* assert something? */
496                 /* from drbd_make_request_common only */
497
498                 hlist_add_head(&req->colision, tl_hash_slot(mdev, req->sector));
499                 /* corresponding hlist_del is in _req_may_be_done() */
500
501                 /* NOTE
502                  * In case the req ended up on the transfer log before being
503                  * queued on the worker, it could lead to this request being
504                  * missed during cleanup after connection loss.
505                  * So we have to do both operations here,
506                  * within the same lock that protects the transfer log.
507                  *
508                  * _req_add_to_epoch(req); this has to be after the
509                  * _maybe_start_new_epoch(req); which happened in
510                  * drbd_make_request_common, because we now may set the bit
511                  * again ourselves to close the current epoch.
512                  *
513                  * Add req to the (now) current epoch (barrier). */
514
515                 /* otherwise we may lose an unplug, which may cause some remote
516                  * io-scheduler timeout to expire, increasing maximum latency,
517                  * hurting performance. */
518                 set_bit(UNPLUG_REMOTE, &mdev->flags);
519
520                 /* see drbd_make_request_common,
521                  * just after it grabs the req_lock */
522                 D_ASSERT(test_bit(CREATE_BARRIER, &mdev->flags) == 0);
523
524                 req->epoch = mdev->newest_tle->br_number;
525                 list_add_tail(&req->tl_requests,
526                                 &mdev->newest_tle->requests);
527
528                 /* increment size of current epoch */
529                 mdev->newest_tle->n_req++;
530
531                 /* queue work item to send data */
532                 D_ASSERT(req->rq_state & RQ_NET_PENDING);
533                 req->rq_state |= RQ_NET_QUEUED;
534                 req->w.cb =  w_send_dblock;
535                 drbd_queue_work(&mdev->data.work, &req->w);
536
537                 /* close the epoch, in case it outgrew the limit */
538                 if (mdev->newest_tle->n_req >= mdev->net_conf->max_epoch_size)
539                         queue_barrier(mdev);
540
541                 break;
542
543         case send_canceled:
544                 /* treat it the same */
545         case send_failed:
546                 /* real cleanup will be done from tl_clear.  just update flags
547                  * so it is no longer marked as on the worker queue */
548                 req->rq_state &= ~RQ_NET_QUEUED;
549                 /* if we did it right, tl_clear should be scheduled only after
550                  * this, so this should not be necessary! */
551                 _req_may_be_done(req, m);
552                 break;
553
554         case handed_over_to_network:
555                 /* assert something? */
556                 if (bio_data_dir(req->master_bio) == WRITE &&
557                     mdev->net_conf->wire_protocol == DRBD_PROT_A) {
558                         /* this is what is dangerous about protocol A:
559                          * pretend it was successfully written on the peer. */
560                         if (req->rq_state & RQ_NET_PENDING) {
561                                 dec_ap_pending(mdev);
562                                 req->rq_state &= ~RQ_NET_PENDING;
563                                 req->rq_state |= RQ_NET_OK;
564                         } /* else: neg-ack was faster... */
565                         /* it is still not yet RQ_NET_DONE until the
566                          * corresponding epoch barrier got acked as well,
567                          * so we know what to dirty on connection loss */
568                 }
569                 req->rq_state &= ~RQ_NET_QUEUED;
570                 req->rq_state |= RQ_NET_SENT;
571                 /* because _drbd_send_zc_bio could sleep, and may want to
572                  * dereference the bio even after the "write_acked_by_peer" and
573                  * "completed_ok" events came in, once we return from
574                  * _drbd_send_zc_bio (drbd_send_dblock), we have to check
575                  * whether it is done already, and end it.  */
576                 _req_may_be_done(req, m);
577                 break;
578
579         case read_retry_remote_canceled:
580                 req->rq_state &= ~RQ_NET_QUEUED;
581                 /* fall through, in case we raced with drbd_disconnect */
582         case connection_lost_while_pending:
583                 /* transfer log cleanup after connection loss */
584                 /* assert something? */
585                 if (req->rq_state & RQ_NET_PENDING)
586                         dec_ap_pending(mdev);
587                 req->rq_state &= ~(RQ_NET_OK|RQ_NET_PENDING);
588                 req->rq_state |= RQ_NET_DONE;
589                 /* if it is still queued, we may not complete it here.
590                  * it will be canceled soon. */
591                 if (!(req->rq_state & RQ_NET_QUEUED))
592                         _req_may_be_done(req, m);
593                 break;
594
595         case write_acked_by_peer_and_sis:
596                 req->rq_state |= RQ_NET_SIS;
597         case conflict_discarded_by_peer:
598                 /* for discarded conflicting writes of multiple primaries,
599                  * there is no need to keep anything in the tl, potential
600                  * node crashes are covered by the activity log. */
601                 if (what == conflict_discarded_by_peer)
602                         dev_alert(DEV, "Got DiscardAck packet %llus +%u!"
603                               " DRBD is not a random data generator!\n",
604                               (unsigned long long)req->sector, req->size);
605                 req->rq_state |= RQ_NET_DONE;
606                 /* fall through */
607         case write_acked_by_peer:
608                 /* protocol C; successfully written on peer.
609                  * Nothing to do here.
610                  * We want to keep the tl in place for all protocols, to cater
611                  * for volatile write-back caches on lower level devices.
612                  *
613                  * A barrier request is expected to have forced all prior
614                  * requests onto stable storage, so completion of a barrier
615                  * request could set NET_DONE right here, and not wait for the
616                  * P_BARRIER_ACK, but that is an unnecessary optimization. */
617
618                 /* this makes it effectively the same as for: */
619         case recv_acked_by_peer:
620                 /* protocol B; pretends to be successfully written on peer.
621                  * see also notes above in handed_over_to_network about
622                  * protocol != C */
623                 req->rq_state |= RQ_NET_OK;
624                 D_ASSERT(req->rq_state & RQ_NET_PENDING);
625                 dec_ap_pending(mdev);
626                 req->rq_state &= ~RQ_NET_PENDING;
627                 _req_may_be_done(req, m);
628                 break;
629
630         case neg_acked:
631                 /* assert something? */
632                 if (req->rq_state & RQ_NET_PENDING)
633                         dec_ap_pending(mdev);
634                 req->rq_state &= ~(RQ_NET_OK|RQ_NET_PENDING);
635
636                 req->rq_state |= RQ_NET_DONE;
637                 _req_may_be_done(req, m);
638                 /* else: done by handed_over_to_network */
639                 break;
640
641         case barrier_acked:
642                 if (req->rq_state & RQ_NET_PENDING) {
643                         /* barrier came in before all requests have been acked.
644                          * this is bad, because if the connection is lost now,
645                          * we won't be able to clean them up... */
646                         dev_err(DEV, "FIXME (barrier_acked but pending)\n");
647                         list_move(&req->tl_requests, &mdev->out_of_sequence_requests);
648                 }
649                 D_ASSERT(req->rq_state & RQ_NET_SENT);
650                 req->rq_state |= RQ_NET_DONE;
651                 _req_may_be_done(req, m);
652                 break;
653
654         case data_received:
655                 D_ASSERT(req->rq_state & RQ_NET_PENDING);
656                 dec_ap_pending(mdev);
657                 req->rq_state &= ~RQ_NET_PENDING;
658                 req->rq_state |= (RQ_NET_OK|RQ_NET_DONE);
659                 _req_may_be_done(req, m);
660                 break;
661         };
662 }
663
664 /* we may do a local read if:
665  * - we are consistent (of course),
666  * - or we are generally inconsistent,
667  *   BUT we are still/already IN SYNC for this area.
668  *   since size may be bigger than BM_BLOCK_SIZE,
669  *   we may need to check several bits.
670  */
671 static int drbd_may_do_local_read(struct drbd_conf *mdev, sector_t sector, int size)
672 {
673         unsigned long sbnr, ebnr;
674         sector_t esector, nr_sectors;
675
676         if (mdev->state.disk == D_UP_TO_DATE)
677                 return 1;
678         if (mdev->state.disk >= D_OUTDATED)
679                 return 0;
680         if (mdev->state.disk <  D_INCONSISTENT)
681                 return 0;
682         /* state.disk == D_INCONSISTENT   We will have a look at the BitMap */
683         nr_sectors = drbd_get_capacity(mdev->this_bdev);
684         esector = sector + (size >> 9) - 1;
685
686         D_ASSERT(sector  < nr_sectors);
687         D_ASSERT(esector < nr_sectors);
688
689         sbnr = BM_SECT_TO_BIT(sector);
690         ebnr = BM_SECT_TO_BIT(esector);
691
692         return 0 == drbd_bm_count_bits(mdev, sbnr, ebnr);
693 }
694
695 static int drbd_make_request_common(struct drbd_conf *mdev, struct bio *bio)
696 {
697         const int rw = bio_rw(bio);
698         const int size = bio->bi_size;
699         const sector_t sector = bio->bi_sector;
700         struct drbd_tl_epoch *b = NULL;
701         struct drbd_request *req;
702         int local, remote;
703         int err = -EIO;
704         int ret = 0;
705
706         /* allocate outside of all locks; */
707         req = drbd_req_new(mdev, bio);
708         if (!req) {
709                 dec_ap_bio(mdev);
710                 /* only pass the error to the upper layers.
711                  * if user cannot handle io errors, that's not our business. */
712                 dev_err(DEV, "could not kmalloc() req\n");
713                 bio_endio(bio, -ENOMEM);
714                 return 0;
715         }
716
717         local = get_ldev(mdev);
718         if (!local) {
719                 bio_put(req->private_bio); /* or we get a bio leak */
720                 req->private_bio = NULL;
721         }
722         if (rw == WRITE) {
723                 remote = 1;
724         } else {
725                 /* READ || READA */
726                 if (local) {
727                         if (!drbd_may_do_local_read(mdev, sector, size)) {
728                                 /* we could kick the syncer to
729                                  * sync this extent asap, wait for
730                                  * it, then continue locally.
731                                  * Or just issue the request remotely.
732                                  */
733                                 local = 0;
734                                 bio_put(req->private_bio);
735                                 req->private_bio = NULL;
736                                 put_ldev(mdev);
737                         }
738                 }
739                 remote = !local && mdev->state.pdsk >= D_UP_TO_DATE;
740         }
741
742         /* If we have a disk, but a READA request is mapped to remote,
743          * we are R_PRIMARY, D_INCONSISTENT, SyncTarget.
744          * Just fail that READA request right here.
745          *
746          * THINK: maybe fail all READA when not local?
747          *        or make this configurable...
748          *        if network is slow, READA won't do any good.
749          */
750         if (rw == READA && mdev->state.disk >= D_INCONSISTENT && !local) {
751                 err = -EWOULDBLOCK;
752                 goto fail_and_free_req;
753         }
754
755         /* For WRITES going to the local disk, grab a reference on the target
756          * extent.  This waits for any resync activity in the corresponding
757          * resync extent to finish, and, if necessary, pulls in the target
758          * extent into the activity log, which involves further disk io because
759          * of transactional on-disk meta data updates. */
760         if (rw == WRITE && local)
761                 drbd_al_begin_io(mdev, sector);
762
763         remote = remote && (mdev->state.pdsk == D_UP_TO_DATE ||
764                             (mdev->state.pdsk == D_INCONSISTENT &&
765                              mdev->state.conn >= C_CONNECTED));
766
767         if (!(local || remote) && !mdev->state.susp) {
768                 dev_err(DEV, "IO ERROR: neither local nor remote disk\n");
769                 goto fail_free_complete;
770         }
771
772         /* For WRITE request, we have to make sure that we have an
773          * unused_spare_tle, in case we need to start a new epoch.
774          * I try to be smart and avoid to pre-allocate always "just in case",
775          * but there is a race between testing the bit and pointer outside the
776          * spinlock, and grabbing the spinlock.
777          * if we lost that race, we retry.  */
778         if (rw == WRITE && remote &&
779             mdev->unused_spare_tle == NULL &&
780             test_bit(CREATE_BARRIER, &mdev->flags)) {
781 allocate_barrier:
782                 b = kmalloc(sizeof(struct drbd_tl_epoch), GFP_NOIO);
783                 if (!b) {
784                         dev_err(DEV, "Failed to alloc barrier.\n");
785                         err = -ENOMEM;
786                         goto fail_free_complete;
787                 }
788         }
789
790         /* GOOD, everything prepared, grab the spin_lock */
791         spin_lock_irq(&mdev->req_lock);
792
793         if (mdev->state.susp) {
794                 /* If we got suspended, use the retry mechanism of
795                    generic_make_request() to restart processing of this
796                    bio. In the next call to drbd_make_request_26
797                    we sleep in inc_ap_bio() */
798                 ret = 1;
799                 spin_unlock_irq(&mdev->req_lock);
800                 goto fail_free_complete;
801         }
802
803         if (remote) {
804                 remote = (mdev->state.pdsk == D_UP_TO_DATE ||
805                             (mdev->state.pdsk == D_INCONSISTENT &&
806                              mdev->state.conn >= C_CONNECTED));
807                 if (!remote)
808                         dev_warn(DEV, "lost connection while grabbing the req_lock!\n");
809                 if (!(local || remote)) {
810                         dev_err(DEV, "IO ERROR: neither local nor remote disk\n");
811                         spin_unlock_irq(&mdev->req_lock);
812                         goto fail_free_complete;
813                 }
814         }
815
816         if (b && mdev->unused_spare_tle == NULL) {
817                 mdev->unused_spare_tle = b;
818                 b = NULL;
819         }
820         if (rw == WRITE && remote &&
821             mdev->unused_spare_tle == NULL &&
822             test_bit(CREATE_BARRIER, &mdev->flags)) {
823                 /* someone closed the current epoch
824                  * while we were grabbing the spinlock */
825                 spin_unlock_irq(&mdev->req_lock);
826                 goto allocate_barrier;
827         }
828
829
830         /* Update disk stats */
831         _drbd_start_io_acct(mdev, req, bio);
832
833         /* _maybe_start_new_epoch(mdev);
834          * If we need to generate a write barrier packet, we have to add the
835          * new epoch (barrier) object, and queue the barrier packet for sending,
836          * and queue the req's data after it _within the same lock_, otherwise
837          * we have race conditions were the reorder domains could be mixed up.
838          *
839          * Even read requests may start a new epoch and queue the corresponding
840          * barrier packet.  To get the write ordering right, we only have to
841          * make sure that, if this is a write request and it triggered a
842          * barrier packet, this request is queued within the same spinlock. */
843         if (remote && mdev->unused_spare_tle &&
844             test_and_clear_bit(CREATE_BARRIER, &mdev->flags)) {
845                 _tl_add_barrier(mdev, mdev->unused_spare_tle);
846                 mdev->unused_spare_tle = NULL;
847         } else {
848                 D_ASSERT(!(remote && rw == WRITE &&
849                            test_bit(CREATE_BARRIER, &mdev->flags)));
850         }
851
852         /* NOTE
853          * Actually, 'local' may be wrong here already, since we may have failed
854          * to write to the meta data, and may become wrong anytime because of
855          * local io-error for some other request, which would lead to us
856          * "detaching" the local disk.
857          *
858          * 'remote' may become wrong any time because the network could fail.
859          *
860          * This is a harmless race condition, though, since it is handled
861          * correctly at the appropriate places; so it just defers the failure
862          * of the respective operation.
863          */
864
865         /* mark them early for readability.
866          * this just sets some state flags. */
867         if (remote)
868                 _req_mod(req, to_be_send);
869         if (local)
870                 _req_mod(req, to_be_submitted);
871
872         /* check this request on the collision detection hash tables.
873          * if we have a conflict, just complete it here.
874          * THINK do we want to check reads, too? (I don't think so...) */
875         if (rw == WRITE && _req_conflicts(req)) {
876                 /* this is a conflicting request.
877                  * even though it may have been only _partially_
878                  * overlapping with one of the currently pending requests,
879                  * without even submitting or sending it, we will
880                  * pretend that it was successfully served right now.
881                  */
882                 if (local) {
883                         bio_put(req->private_bio);
884                         req->private_bio = NULL;
885                         drbd_al_complete_io(mdev, req->sector);
886                         put_ldev(mdev);
887                         local = 0;
888                 }
889                 if (remote)
890                         dec_ap_pending(mdev);
891                 _drbd_end_io_acct(mdev, req);
892                 /* THINK: do we want to fail it (-EIO), or pretend success? */
893                 bio_endio(req->master_bio, 0);
894                 req->master_bio = NULL;
895                 dec_ap_bio(mdev);
896                 drbd_req_free(req);
897                 remote = 0;
898         }
899
900         /* NOTE remote first: to get the concurrent write detection right,
901          * we must register the request before start of local IO.  */
902         if (remote) {
903                 /* either WRITE and C_CONNECTED,
904                  * or READ, and no local disk,
905                  * or READ, but not in sync.
906                  */
907                 _req_mod(req, (rw == WRITE)
908                                 ? queue_for_net_write
909                                 : queue_for_net_read);
910         }
911         spin_unlock_irq(&mdev->req_lock);
912         kfree(b); /* if someone else has beaten us to it... */
913
914         if (local) {
915                 req->private_bio->bi_bdev = mdev->ldev->backing_bdev;
916
917                 if (FAULT_ACTIVE(mdev, rw == WRITE ? DRBD_FAULT_DT_WR
918                                      : rw == READ  ? DRBD_FAULT_DT_RD
919                                      :               DRBD_FAULT_DT_RA))
920                         bio_endio(req->private_bio, -EIO);
921                 else
922                         generic_make_request(req->private_bio);
923         }
924
925         /* we need to plug ALWAYS since we possibly need to kick lo_dev.
926          * we plug after submit, so we won't miss an unplug event */
927         drbd_plug_device(mdev);
928
929         return 0;
930
931 fail_free_complete:
932         if (rw == WRITE && local)
933                 drbd_al_complete_io(mdev, sector);
934 fail_and_free_req:
935         if (local) {
936                 bio_put(req->private_bio);
937                 req->private_bio = NULL;
938                 put_ldev(mdev);
939         }
940         if (!ret)
941                 bio_endio(bio, err);
942
943         drbd_req_free(req);
944         dec_ap_bio(mdev);
945         kfree(b);
946
947         return ret;
948 }
949
950 /* helper function for drbd_make_request
951  * if we can determine just by the mdev (state) that this request will fail,
952  * return 1
953  * otherwise return 0
954  */
955 static int drbd_fail_request_early(struct drbd_conf *mdev, int is_write)
956 {
957         if (mdev->state.role != R_PRIMARY &&
958                 (!allow_oos || is_write)) {
959                 if (__ratelimit(&drbd_ratelimit_state)) {
960                         dev_err(DEV, "Process %s[%u] tried to %s; "
961                             "since we are not in Primary state, "
962                             "we cannot allow this\n",
963                             current->comm, current->pid,
964                             is_write ? "WRITE" : "READ");
965                 }
966                 return 1;
967         }
968
969         /*
970          * Paranoia: we might have been primary, but sync target, or
971          * even diskless, then lost the connection.
972          * This should have been handled (panic? suspend?) somewhere
973          * else. But maybe it was not, so check again here.
974          * Caution: as long as we do not have a read/write lock on mdev,
975          * to serialize state changes, this is racy, since we may lose
976          * the connection *after* we test for the cstate.
977          */
978         if (mdev->state.disk < D_UP_TO_DATE && mdev->state.pdsk < D_UP_TO_DATE) {
979                 if (__ratelimit(&drbd_ratelimit_state))
980                         dev_err(DEV, "Sorry, I have no access to good data anymore.\n");
981                 return 1;
982         }
983
984         return 0;
985 }
986
987 int drbd_make_request_26(struct request_queue *q, struct bio *bio)
988 {
989         unsigned int s_enr, e_enr;
990         struct drbd_conf *mdev = (struct drbd_conf *) q->queuedata;
991
992         if (drbd_fail_request_early(mdev, bio_data_dir(bio) & WRITE)) {
993                 bio_endio(bio, -EPERM);
994                 return 0;
995         }
996
997         /* Reject barrier requests if we know the underlying device does
998          * not support them.
999          * XXX: Need to get this info from peer as well some how so we
1000          * XXX: reject if EITHER side/data/metadata area does not support them.
1001          *
1002          * because of those XXX, this is not yet enabled,
1003          * i.e. in drbd_init_set_defaults we set the NO_BARRIER_SUPP bit.
1004          */
1005         if (unlikely(bio_rw_flagged(bio, BIO_RW_BARRIER) && test_bit(NO_BARRIER_SUPP, &mdev->flags))) {
1006                 /* dev_warn(DEV, "Rejecting barrier request as underlying device does not support\n"); */
1007                 bio_endio(bio, -EOPNOTSUPP);
1008                 return 0;
1009         }
1010
1011         /*
1012          * what we "blindly" assume:
1013          */
1014         D_ASSERT(bio->bi_size > 0);
1015         D_ASSERT((bio->bi_size & 0x1ff) == 0);
1016         D_ASSERT(bio->bi_idx == 0);
1017
1018         /* to make some things easier, force alignment of requests within the
1019          * granularity of our hash tables */
1020         s_enr = bio->bi_sector >> HT_SHIFT;
1021         e_enr = (bio->bi_sector+(bio->bi_size>>9)-1) >> HT_SHIFT;
1022
1023         if (likely(s_enr == e_enr)) {
1024                 inc_ap_bio(mdev, 1);
1025                 return drbd_make_request_common(mdev, bio);
1026         }
1027
1028         /* can this bio be split generically?
1029          * Maybe add our own split-arbitrary-bios function. */
1030         if (bio->bi_vcnt != 1 || bio->bi_idx != 0 || bio->bi_size > DRBD_MAX_SEGMENT_SIZE) {
1031                 /* rather error out here than BUG in bio_split */
1032                 dev_err(DEV, "bio would need to, but cannot, be split: "
1033                     "(vcnt=%u,idx=%u,size=%u,sector=%llu)\n",
1034                     bio->bi_vcnt, bio->bi_idx, bio->bi_size,
1035                     (unsigned long long)bio->bi_sector);
1036                 bio_endio(bio, -EINVAL);
1037         } else {
1038                 /* This bio crosses some boundary, so we have to split it. */
1039                 struct bio_pair *bp;
1040                 /* works for the "do not cross hash slot boundaries" case
1041                  * e.g. sector 262269, size 4096
1042                  * s_enr = 262269 >> 6 = 4097
1043                  * e_enr = (262269+8-1) >> 6 = 4098
1044                  * HT_SHIFT = 6
1045                  * sps = 64, mask = 63
1046                  * first_sectors = 64 - (262269 & 63) = 3
1047                  */
1048                 const sector_t sect = bio->bi_sector;
1049                 const int sps = 1 << HT_SHIFT; /* sectors per slot */
1050                 const int mask = sps - 1;
1051                 const sector_t first_sectors = sps - (sect & mask);
1052                 bp = bio_split(bio,
1053 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,28)
1054                                 bio_split_pool,
1055 #endif
1056                                 first_sectors);
1057
1058                 /* we need to get a "reference count" (ap_bio_cnt)
1059                  * to avoid races with the disconnect/reconnect/suspend code.
1060                  * In case we need to split the bio here, we need to get three references
1061                  * atomically, otherwise we might deadlock when trying to submit the
1062                  * second one! */
1063                 inc_ap_bio(mdev, 3);
1064
1065                 D_ASSERT(e_enr == s_enr + 1);
1066
1067                 while (drbd_make_request_common(mdev, &bp->bio1))
1068                         inc_ap_bio(mdev, 1);
1069
1070                 while (drbd_make_request_common(mdev, &bp->bio2))
1071                         inc_ap_bio(mdev, 1);
1072
1073                 dec_ap_bio(mdev);
1074
1075                 bio_pair_release(bp);
1076         }
1077         return 0;
1078 }
1079
1080 /* This is called by bio_add_page().  With this function we reduce
1081  * the number of BIOs that span over multiple DRBD_MAX_SEGMENT_SIZEs
1082  * units (was AL_EXTENTs).
1083  *
1084  * we do the calculation within the lower 32bit of the byte offsets,
1085  * since we don't care for actual offset, but only check whether it
1086  * would cross "activity log extent" boundaries.
1087  *
1088  * As long as the BIO is empty we have to allow at least one bvec,
1089  * regardless of size and offset.  so the resulting bio may still
1090  * cross extent boundaries.  those are dealt with (bio_split) in
1091  * drbd_make_request_26.
1092  */
1093 int drbd_merge_bvec(struct request_queue *q, struct bvec_merge_data *bvm, struct bio_vec *bvec)
1094 {
1095         struct drbd_conf *mdev = (struct drbd_conf *) q->queuedata;
1096         unsigned int bio_offset =
1097                 (unsigned int)bvm->bi_sector << 9; /* 32 bit */
1098         unsigned int bio_size = bvm->bi_size;
1099         int limit, backing_limit;
1100
1101         limit = DRBD_MAX_SEGMENT_SIZE
1102               - ((bio_offset & (DRBD_MAX_SEGMENT_SIZE-1)) + bio_size);
1103         if (limit < 0)
1104                 limit = 0;
1105         if (bio_size == 0) {
1106                 if (limit <= bvec->bv_len)
1107                         limit = bvec->bv_len;
1108         } else if (limit && get_ldev(mdev)) {
1109                 struct request_queue * const b =
1110                         mdev->ldev->backing_bdev->bd_disk->queue;
1111                 if (b->merge_bvec_fn) {
1112                         backing_limit = b->merge_bvec_fn(b, bvm, bvec);
1113                         limit = min(limit, backing_limit);
1114                 }
1115                 put_ldev(mdev);
1116         }
1117         return limit;
1118 }