xref: /openbmc/linux/drivers/block/drbd/drbd_nl.c (revision 4800cd83)
1 /*
2    drbd_nl.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 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/connector.h>
33 #include <linux/blkpg.h>
34 #include <linux/cpumask.h>
35 #include "drbd_int.h"
36 #include "drbd_req.h"
37 #include "drbd_wrappers.h"
38 #include <asm/unaligned.h>
39 #include <linux/drbd_tag_magic.h>
40 #include <linux/drbd_limits.h>
41 #include <linux/compiler.h>
42 #include <linux/kthread.h>
43 
44 static unsigned short *tl_add_blob(unsigned short *, enum drbd_tags, const void *, int);
45 static unsigned short *tl_add_str(unsigned short *, enum drbd_tags, const char *);
46 static unsigned short *tl_add_int(unsigned short *, enum drbd_tags, const void *);
47 
48 /* see get_sb_bdev and bd_claim */
49 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
50 
51 /* Generate the tag_list to struct functions */
52 #define NL_PACKET(name, number, fields) \
53 static int name ## _from_tags(struct drbd_conf *mdev, \
54 	unsigned short *tags, struct name *arg) __attribute__ ((unused)); \
55 static int name ## _from_tags(struct drbd_conf *mdev, \
56 	unsigned short *tags, struct name *arg) \
57 { \
58 	int tag; \
59 	int dlen; \
60 	\
61 	while ((tag = get_unaligned(tags++)) != TT_END) {	\
62 		dlen = get_unaligned(tags++);			\
63 		switch (tag_number(tag)) { \
64 		fields \
65 		default: \
66 			if (tag & T_MANDATORY) { \
67 				dev_err(DEV, "Unknown tag: %d\n", tag_number(tag)); \
68 				return 0; \
69 			} \
70 		} \
71 		tags = (unsigned short *)((char *)tags + dlen); \
72 	} \
73 	return 1; \
74 }
75 #define NL_INTEGER(pn, pr, member) \
76 	case pn: /* D_ASSERT( tag_type(tag) == TT_INTEGER ); */ \
77 		arg->member = get_unaligned((int *)(tags));	\
78 		break;
79 #define NL_INT64(pn, pr, member) \
80 	case pn: /* D_ASSERT( tag_type(tag) == TT_INT64 ); */ \
81 		arg->member = get_unaligned((u64 *)(tags));	\
82 		break;
83 #define NL_BIT(pn, pr, member) \
84 	case pn: /* D_ASSERT( tag_type(tag) == TT_BIT ); */ \
85 		arg->member = *(char *)(tags) ? 1 : 0; \
86 		break;
87 #define NL_STRING(pn, pr, member, len) \
88 	case pn: /* D_ASSERT( tag_type(tag) == TT_STRING ); */ \
89 		if (dlen > len) { \
90 			dev_err(DEV, "arg too long: %s (%u wanted, max len: %u bytes)\n", \
91 				#member, dlen, (unsigned int)len); \
92 			return 0; \
93 		} \
94 		 arg->member ## _len = dlen; \
95 		 memcpy(arg->member, tags, min_t(size_t, dlen, len)); \
96 		 break;
97 #include "linux/drbd_nl.h"
98 
99 /* Generate the struct to tag_list functions */
100 #define NL_PACKET(name, number, fields) \
101 static unsigned short* \
102 name ## _to_tags(struct drbd_conf *mdev, \
103 	struct name *arg, unsigned short *tags) __attribute__ ((unused)); \
104 static unsigned short* \
105 name ## _to_tags(struct drbd_conf *mdev, \
106 	struct name *arg, unsigned short *tags) \
107 { \
108 	fields \
109 	return tags; \
110 }
111 
112 #define NL_INTEGER(pn, pr, member) \
113 	put_unaligned(pn | pr | TT_INTEGER, tags++);	\
114 	put_unaligned(sizeof(int), tags++);		\
115 	put_unaligned(arg->member, (int *)tags);	\
116 	tags = (unsigned short *)((char *)tags+sizeof(int));
117 #define NL_INT64(pn, pr, member) \
118 	put_unaligned(pn | pr | TT_INT64, tags++);	\
119 	put_unaligned(sizeof(u64), tags++);		\
120 	put_unaligned(arg->member, (u64 *)tags);	\
121 	tags = (unsigned short *)((char *)tags+sizeof(u64));
122 #define NL_BIT(pn, pr, member) \
123 	put_unaligned(pn | pr | TT_BIT, tags++);	\
124 	put_unaligned(sizeof(char), tags++);		\
125 	*(char *)tags = arg->member; \
126 	tags = (unsigned short *)((char *)tags+sizeof(char));
127 #define NL_STRING(pn, pr, member, len) \
128 	put_unaligned(pn | pr | TT_STRING, tags++);	\
129 	put_unaligned(arg->member ## _len, tags++);	\
130 	memcpy(tags, arg->member, arg->member ## _len); \
131 	tags = (unsigned short *)((char *)tags + arg->member ## _len);
132 #include "linux/drbd_nl.h"
133 
134 void drbd_bcast_ev_helper(struct drbd_conf *mdev, char *helper_name);
135 void drbd_nl_send_reply(struct cn_msg *, int);
136 
137 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
138 {
139 	char *envp[] = { "HOME=/",
140 			"TERM=linux",
141 			"PATH=/sbin:/usr/sbin:/bin:/usr/bin",
142 			NULL, /* Will be set to address family */
143 			NULL, /* Will be set to address */
144 			NULL };
145 
146 	char mb[12], af[20], ad[60], *afs;
147 	char *argv[] = {usermode_helper, cmd, mb, NULL };
148 	int ret;
149 
150 	snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
151 
152 	if (get_net_conf(mdev)) {
153 		switch (((struct sockaddr *)mdev->net_conf->peer_addr)->sa_family) {
154 		case AF_INET6:
155 			afs = "ipv6";
156 			snprintf(ad, 60, "DRBD_PEER_ADDRESS=%pI6",
157 				 &((struct sockaddr_in6 *)mdev->net_conf->peer_addr)->sin6_addr);
158 			break;
159 		case AF_INET:
160 			afs = "ipv4";
161 			snprintf(ad, 60, "DRBD_PEER_ADDRESS=%pI4",
162 				 &((struct sockaddr_in *)mdev->net_conf->peer_addr)->sin_addr);
163 			break;
164 		default:
165 			afs = "ssocks";
166 			snprintf(ad, 60, "DRBD_PEER_ADDRESS=%pI4",
167 				 &((struct sockaddr_in *)mdev->net_conf->peer_addr)->sin_addr);
168 		}
169 		snprintf(af, 20, "DRBD_PEER_AF=%s", afs);
170 		envp[3]=af;
171 		envp[4]=ad;
172 		put_net_conf(mdev);
173 	}
174 
175 	/* The helper may take some time.
176 	 * write out any unsynced meta data changes now */
177 	drbd_md_sync(mdev);
178 
179 	dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
180 
181 	drbd_bcast_ev_helper(mdev, cmd);
182 	ret = call_usermodehelper(usermode_helper, argv, envp, 1);
183 	if (ret)
184 		dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
185 				usermode_helper, cmd, mb,
186 				(ret >> 8) & 0xff, ret);
187 	else
188 		dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
189 				usermode_helper, cmd, mb,
190 				(ret >> 8) & 0xff, ret);
191 
192 	if (ret < 0) /* Ignore any ERRNOs we got. */
193 		ret = 0;
194 
195 	return ret;
196 }
197 
198 enum drbd_disk_state drbd_try_outdate_peer(struct drbd_conf *mdev)
199 {
200 	char *ex_to_string;
201 	int r;
202 	enum drbd_disk_state nps;
203 	enum drbd_fencing_p fp;
204 
205 	D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
206 
207 	if (get_ldev_if_state(mdev, D_CONSISTENT)) {
208 		fp = mdev->ldev->dc.fencing;
209 		put_ldev(mdev);
210 	} else {
211 		dev_warn(DEV, "Not fencing peer, I'm not even Consistent myself.\n");
212 		nps = mdev->state.pdsk;
213 		goto out;
214 	}
215 
216 	r = drbd_khelper(mdev, "fence-peer");
217 
218 	switch ((r>>8) & 0xff) {
219 	case 3: /* peer is inconsistent */
220 		ex_to_string = "peer is inconsistent or worse";
221 		nps = D_INCONSISTENT;
222 		break;
223 	case 4: /* peer got outdated, or was already outdated */
224 		ex_to_string = "peer was fenced";
225 		nps = D_OUTDATED;
226 		break;
227 	case 5: /* peer was down */
228 		if (mdev->state.disk == D_UP_TO_DATE) {
229 			/* we will(have) create(d) a new UUID anyways... */
230 			ex_to_string = "peer is unreachable, assumed to be dead";
231 			nps = D_OUTDATED;
232 		} else {
233 			ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
234 			nps = mdev->state.pdsk;
235 		}
236 		break;
237 	case 6: /* Peer is primary, voluntarily outdate myself.
238 		 * This is useful when an unconnected R_SECONDARY is asked to
239 		 * become R_PRIMARY, but finds the other peer being active. */
240 		ex_to_string = "peer is active";
241 		dev_warn(DEV, "Peer is primary, outdating myself.\n");
242 		nps = D_UNKNOWN;
243 		_drbd_request_state(mdev, NS(disk, D_OUTDATED), CS_WAIT_COMPLETE);
244 		break;
245 	case 7:
246 		if (fp != FP_STONITH)
247 			dev_err(DEV, "fence-peer() = 7 && fencing != Stonith !!!\n");
248 		ex_to_string = "peer was stonithed";
249 		nps = D_OUTDATED;
250 		break;
251 	default:
252 		/* The script is broken ... */
253 		nps = D_UNKNOWN;
254 		dev_err(DEV, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
255 		return nps;
256 	}
257 
258 	dev_info(DEV, "fence-peer helper returned %d (%s)\n",
259 			(r>>8) & 0xff, ex_to_string);
260 
261 out:
262 	if (mdev->state.susp_fen && nps >= D_UNKNOWN) {
263 		/* The handler was not successful... unfreeze here, the
264 		   state engine can not unfreeze... */
265 		_drbd_request_state(mdev, NS(susp_fen, 0), CS_VERBOSE);
266 	}
267 
268 	return nps;
269 }
270 
271 static int _try_outdate_peer_async(void *data)
272 {
273 	struct drbd_conf *mdev = (struct drbd_conf *)data;
274 	enum drbd_disk_state nps;
275 
276 	nps = drbd_try_outdate_peer(mdev);
277 	drbd_request_state(mdev, NS(pdsk, nps));
278 
279 	return 0;
280 }
281 
282 void drbd_try_outdate_peer_async(struct drbd_conf *mdev)
283 {
284 	struct task_struct *opa;
285 
286 	opa = kthread_run(_try_outdate_peer_async, mdev, "drbd%d_a_helper", mdev_to_minor(mdev));
287 	if (IS_ERR(opa))
288 		dev_err(DEV, "out of mem, failed to invoke fence-peer helper\n");
289 }
290 
291 int drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
292 {
293 	const int max_tries = 4;
294 	int r = 0;
295 	int try = 0;
296 	int forced = 0;
297 	union drbd_state mask, val;
298 	enum drbd_disk_state nps;
299 
300 	if (new_role == R_PRIMARY)
301 		request_ping(mdev); /* Detect a dead peer ASAP */
302 
303 	mutex_lock(&mdev->state_mutex);
304 
305 	mask.i = 0; mask.role = R_MASK;
306 	val.i  = 0; val.role  = new_role;
307 
308 	while (try++ < max_tries) {
309 		r = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
310 
311 		/* in case we first succeeded to outdate,
312 		 * but now suddenly could establish a connection */
313 		if (r == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
314 			val.pdsk = 0;
315 			mask.pdsk = 0;
316 			continue;
317 		}
318 
319 		if (r == SS_NO_UP_TO_DATE_DISK && force &&
320 		    (mdev->state.disk < D_UP_TO_DATE &&
321 		     mdev->state.disk >= D_INCONSISTENT)) {
322 			mask.disk = D_MASK;
323 			val.disk  = D_UP_TO_DATE;
324 			forced = 1;
325 			continue;
326 		}
327 
328 		if (r == SS_NO_UP_TO_DATE_DISK &&
329 		    mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
330 			D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
331 			nps = drbd_try_outdate_peer(mdev);
332 
333 			if (nps == D_OUTDATED || nps == D_INCONSISTENT) {
334 				val.disk = D_UP_TO_DATE;
335 				mask.disk = D_MASK;
336 			}
337 
338 			val.pdsk = nps;
339 			mask.pdsk = D_MASK;
340 
341 			continue;
342 		}
343 
344 		if (r == SS_NOTHING_TO_DO)
345 			goto fail;
346 		if (r == SS_PRIMARY_NOP && mask.pdsk == 0) {
347 			nps = drbd_try_outdate_peer(mdev);
348 
349 			if (force && nps > D_OUTDATED) {
350 				dev_warn(DEV, "Forced into split brain situation!\n");
351 				nps = D_OUTDATED;
352 			}
353 
354 			mask.pdsk = D_MASK;
355 			val.pdsk  = nps;
356 
357 			continue;
358 		}
359 		if (r == SS_TWO_PRIMARIES) {
360 			/* Maybe the peer is detected as dead very soon...
361 			   retry at most once more in this case. */
362 			__set_current_state(TASK_INTERRUPTIBLE);
363 			schedule_timeout((mdev->net_conf->ping_timeo+1)*HZ/10);
364 			if (try < max_tries)
365 				try = max_tries - 1;
366 			continue;
367 		}
368 		if (r < SS_SUCCESS) {
369 			r = _drbd_request_state(mdev, mask, val,
370 						CS_VERBOSE + CS_WAIT_COMPLETE);
371 			if (r < SS_SUCCESS)
372 				goto fail;
373 		}
374 		break;
375 	}
376 
377 	if (r < SS_SUCCESS)
378 		goto fail;
379 
380 	if (forced)
381 		dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
382 
383 	/* Wait until nothing is on the fly :) */
384 	wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
385 
386 	if (new_role == R_SECONDARY) {
387 		set_disk_ro(mdev->vdisk, TRUE);
388 		if (get_ldev(mdev)) {
389 			mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
390 			put_ldev(mdev);
391 		}
392 	} else {
393 		if (get_net_conf(mdev)) {
394 			mdev->net_conf->want_lose = 0;
395 			put_net_conf(mdev);
396 		}
397 		set_disk_ro(mdev->vdisk, FALSE);
398 		if (get_ldev(mdev)) {
399 			if (((mdev->state.conn < C_CONNECTED ||
400 			       mdev->state.pdsk <= D_FAILED)
401 			      && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
402 				drbd_uuid_new_current(mdev);
403 
404 			mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
405 			put_ldev(mdev);
406 		}
407 	}
408 
409 	if ((new_role == R_SECONDARY) && get_ldev(mdev)) {
410 		drbd_al_to_on_disk_bm(mdev);
411 		put_ldev(mdev);
412 	}
413 
414 	if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
415 		/* if this was forced, we should consider sync */
416 		if (forced)
417 			drbd_send_uuids(mdev);
418 		drbd_send_state(mdev);
419 	}
420 
421 	drbd_md_sync(mdev);
422 
423 	kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
424  fail:
425 	mutex_unlock(&mdev->state_mutex);
426 	return r;
427 }
428 
429 static struct drbd_conf *ensure_mdev(int minor, int create)
430 {
431 	struct drbd_conf *mdev;
432 
433 	if (minor >= minor_count)
434 		return NULL;
435 
436 	mdev = minor_to_mdev(minor);
437 
438 	if (!mdev && create) {
439 		struct gendisk *disk = NULL;
440 		mdev = drbd_new_device(minor);
441 
442 		spin_lock_irq(&drbd_pp_lock);
443 		if (minor_table[minor] == NULL) {
444 			minor_table[minor] = mdev;
445 			disk = mdev->vdisk;
446 			mdev = NULL;
447 		} /* else: we lost the race */
448 		spin_unlock_irq(&drbd_pp_lock);
449 
450 		if (disk) /* we won the race above */
451 			/* in case we ever add a drbd_delete_device(),
452 			 * don't forget the del_gendisk! */
453 			add_disk(disk);
454 		else /* we lost the race above */
455 			drbd_free_mdev(mdev);
456 
457 		mdev = minor_to_mdev(minor);
458 	}
459 
460 	return mdev;
461 }
462 
463 static int drbd_nl_primary(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
464 			   struct drbd_nl_cfg_reply *reply)
465 {
466 	struct primary primary_args;
467 
468 	memset(&primary_args, 0, sizeof(struct primary));
469 	if (!primary_from_tags(mdev, nlp->tag_list, &primary_args)) {
470 		reply->ret_code = ERR_MANDATORY_TAG;
471 		return 0;
472 	}
473 
474 	reply->ret_code =
475 		drbd_set_role(mdev, R_PRIMARY, primary_args.primary_force);
476 
477 	return 0;
478 }
479 
480 static int drbd_nl_secondary(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
481 			     struct drbd_nl_cfg_reply *reply)
482 {
483 	reply->ret_code = drbd_set_role(mdev, R_SECONDARY, 0);
484 
485 	return 0;
486 }
487 
488 /* initializes the md.*_offset members, so we are able to find
489  * the on disk meta data */
490 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
491 				       struct drbd_backing_dev *bdev)
492 {
493 	sector_t md_size_sect = 0;
494 	switch (bdev->dc.meta_dev_idx) {
495 	default:
496 		/* v07 style fixed size indexed meta data */
497 		bdev->md.md_size_sect = MD_RESERVED_SECT;
498 		bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
499 		bdev->md.al_offset = MD_AL_OFFSET;
500 		bdev->md.bm_offset = MD_BM_OFFSET;
501 		break;
502 	case DRBD_MD_INDEX_FLEX_EXT:
503 		/* just occupy the full device; unit: sectors */
504 		bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
505 		bdev->md.md_offset = 0;
506 		bdev->md.al_offset = MD_AL_OFFSET;
507 		bdev->md.bm_offset = MD_BM_OFFSET;
508 		break;
509 	case DRBD_MD_INDEX_INTERNAL:
510 	case DRBD_MD_INDEX_FLEX_INT:
511 		bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
512 		/* al size is still fixed */
513 		bdev->md.al_offset = -MD_AL_MAX_SIZE;
514 		/* we need (slightly less than) ~ this much bitmap sectors: */
515 		md_size_sect = drbd_get_capacity(bdev->backing_bdev);
516 		md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
517 		md_size_sect = BM_SECT_TO_EXT(md_size_sect);
518 		md_size_sect = ALIGN(md_size_sect, 8);
519 
520 		/* plus the "drbd meta data super block",
521 		 * and the activity log; */
522 		md_size_sect += MD_BM_OFFSET;
523 
524 		bdev->md.md_size_sect = md_size_sect;
525 		/* bitmap offset is adjusted by 'super' block size */
526 		bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
527 		break;
528 	}
529 }
530 
531 char *ppsize(char *buf, unsigned long long size)
532 {
533 	/* Needs 9 bytes at max. */
534 	static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
535 	int base = 0;
536 	while (size >= 10000) {
537 		/* shift + round */
538 		size = (size >> 10) + !!(size & (1<<9));
539 		base++;
540 	}
541 	sprintf(buf, "%lu %cB", (long)size, units[base]);
542 
543 	return buf;
544 }
545 
546 /* there is still a theoretical deadlock when called from receiver
547  * on an D_INCONSISTENT R_PRIMARY:
548  *  remote READ does inc_ap_bio, receiver would need to receive answer
549  *  packet from remote to dec_ap_bio again.
550  *  receiver receive_sizes(), comes here,
551  *  waits for ap_bio_cnt == 0. -> deadlock.
552  * but this cannot happen, actually, because:
553  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
554  *  (not connected, or bad/no disk on peer):
555  *  see drbd_fail_request_early, ap_bio_cnt is zero.
556  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
557  *  peer may not initiate a resize.
558  */
559 void drbd_suspend_io(struct drbd_conf *mdev)
560 {
561 	set_bit(SUSPEND_IO, &mdev->flags);
562 	if (is_susp(mdev->state))
563 		return;
564 	wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
565 }
566 
567 void drbd_resume_io(struct drbd_conf *mdev)
568 {
569 	clear_bit(SUSPEND_IO, &mdev->flags);
570 	wake_up(&mdev->misc_wait);
571 }
572 
573 /**
574  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
575  * @mdev:	DRBD device.
576  *
577  * Returns 0 on success, negative return values indicate errors.
578  * You should call drbd_md_sync() after calling this function.
579  */
580 enum determine_dev_size drbd_determin_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
581 {
582 	sector_t prev_first_sect, prev_size; /* previous meta location */
583 	sector_t la_size;
584 	sector_t size;
585 	char ppb[10];
586 
587 	int md_moved, la_size_changed;
588 	enum determine_dev_size rv = unchanged;
589 
590 	/* race:
591 	 * application request passes inc_ap_bio,
592 	 * but then cannot get an AL-reference.
593 	 * this function later may wait on ap_bio_cnt == 0. -> deadlock.
594 	 *
595 	 * to avoid that:
596 	 * Suspend IO right here.
597 	 * still lock the act_log to not trigger ASSERTs there.
598 	 */
599 	drbd_suspend_io(mdev);
600 
601 	/* no wait necessary anymore, actually we could assert that */
602 	wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
603 
604 	prev_first_sect = drbd_md_first_sector(mdev->ldev);
605 	prev_size = mdev->ldev->md.md_size_sect;
606 	la_size = mdev->ldev->md.la_size_sect;
607 
608 	/* TODO: should only be some assert here, not (re)init... */
609 	drbd_md_set_sector_offsets(mdev, mdev->ldev);
610 
611 	size = drbd_new_dev_size(mdev, mdev->ldev, flags & DDSF_FORCED);
612 
613 	if (drbd_get_capacity(mdev->this_bdev) != size ||
614 	    drbd_bm_capacity(mdev) != size) {
615 		int err;
616 		err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
617 		if (unlikely(err)) {
618 			/* currently there is only one error: ENOMEM! */
619 			size = drbd_bm_capacity(mdev)>>1;
620 			if (size == 0) {
621 				dev_err(DEV, "OUT OF MEMORY! "
622 				    "Could not allocate bitmap!\n");
623 			} else {
624 				dev_err(DEV, "BM resizing failed. "
625 				    "Leaving size unchanged at size = %lu KB\n",
626 				    (unsigned long)size);
627 			}
628 			rv = dev_size_error;
629 		}
630 		/* racy, see comments above. */
631 		drbd_set_my_capacity(mdev, size);
632 		mdev->ldev->md.la_size_sect = size;
633 		dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
634 		     (unsigned long long)size>>1);
635 	}
636 	if (rv == dev_size_error)
637 		goto out;
638 
639 	la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
640 
641 	md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
642 		|| prev_size	   != mdev->ldev->md.md_size_sect;
643 
644 	if (la_size_changed || md_moved) {
645 		drbd_al_shrink(mdev); /* All extents inactive. */
646 		dev_info(DEV, "Writing the whole bitmap, %s\n",
647 			 la_size_changed && md_moved ? "size changed and md moved" :
648 			 la_size_changed ? "size changed" : "md moved");
649 		rv = drbd_bitmap_io(mdev, &drbd_bm_write, "size changed"); /* does drbd_resume_io() ! */
650 		drbd_md_mark_dirty(mdev);
651 	}
652 
653 	if (size > la_size)
654 		rv = grew;
655 	if (size < la_size)
656 		rv = shrunk;
657 out:
658 	lc_unlock(mdev->act_log);
659 	wake_up(&mdev->al_wait);
660 	drbd_resume_io(mdev);
661 
662 	return rv;
663 }
664 
665 sector_t
666 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev, int assume_peer_has_space)
667 {
668 	sector_t p_size = mdev->p_size;   /* partner's disk size. */
669 	sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
670 	sector_t m_size; /* my size */
671 	sector_t u_size = bdev->dc.disk_size; /* size requested by user. */
672 	sector_t size = 0;
673 
674 	m_size = drbd_get_max_capacity(bdev);
675 
676 	if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
677 		dev_warn(DEV, "Resize while not connected was forced by the user!\n");
678 		p_size = m_size;
679 	}
680 
681 	if (p_size && m_size) {
682 		size = min_t(sector_t, p_size, m_size);
683 	} else {
684 		if (la_size) {
685 			size = la_size;
686 			if (m_size && m_size < size)
687 				size = m_size;
688 			if (p_size && p_size < size)
689 				size = p_size;
690 		} else {
691 			if (m_size)
692 				size = m_size;
693 			if (p_size)
694 				size = p_size;
695 		}
696 	}
697 
698 	if (size == 0)
699 		dev_err(DEV, "Both nodes diskless!\n");
700 
701 	if (u_size) {
702 		if (u_size > size)
703 			dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
704 			    (unsigned long)u_size>>1, (unsigned long)size>>1);
705 		else
706 			size = u_size;
707 	}
708 
709 	return size;
710 }
711 
712 /**
713  * drbd_check_al_size() - Ensures that the AL is of the right size
714  * @mdev:	DRBD device.
715  *
716  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
717  * failed, and 0 on success. You should call drbd_md_sync() after you called
718  * this function.
719  */
720 static int drbd_check_al_size(struct drbd_conf *mdev)
721 {
722 	struct lru_cache *n, *t;
723 	struct lc_element *e;
724 	unsigned int in_use;
725 	int i;
726 
727 	ERR_IF(mdev->sync_conf.al_extents < 7)
728 		mdev->sync_conf.al_extents = 127;
729 
730 	if (mdev->act_log &&
731 	    mdev->act_log->nr_elements == mdev->sync_conf.al_extents)
732 		return 0;
733 
734 	in_use = 0;
735 	t = mdev->act_log;
736 	n = lc_create("act_log", drbd_al_ext_cache,
737 		mdev->sync_conf.al_extents, sizeof(struct lc_element), 0);
738 
739 	if (n == NULL) {
740 		dev_err(DEV, "Cannot allocate act_log lru!\n");
741 		return -ENOMEM;
742 	}
743 	spin_lock_irq(&mdev->al_lock);
744 	if (t) {
745 		for (i = 0; i < t->nr_elements; i++) {
746 			e = lc_element_by_index(t, i);
747 			if (e->refcnt)
748 				dev_err(DEV, "refcnt(%d)==%d\n",
749 				    e->lc_number, e->refcnt);
750 			in_use += e->refcnt;
751 		}
752 	}
753 	if (!in_use)
754 		mdev->act_log = n;
755 	spin_unlock_irq(&mdev->al_lock);
756 	if (in_use) {
757 		dev_err(DEV, "Activity log still in use!\n");
758 		lc_destroy(n);
759 		return -EBUSY;
760 	} else {
761 		if (t)
762 			lc_destroy(t);
763 	}
764 	drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
765 	return 0;
766 }
767 
768 void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_seg_s) __must_hold(local)
769 {
770 	struct request_queue * const q = mdev->rq_queue;
771 	struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
772 	int max_segments = mdev->ldev->dc.max_bio_bvecs;
773 
774 	max_seg_s = min(queue_max_sectors(b) * queue_logical_block_size(b), max_seg_s);
775 
776 	blk_queue_max_hw_sectors(q, max_seg_s >> 9);
777 	blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
778 	blk_queue_max_segment_size(q, max_seg_s);
779 	blk_queue_logical_block_size(q, 512);
780 	blk_queue_segment_boundary(q, PAGE_SIZE-1);
781 	blk_stack_limits(&q->limits, &b->limits, 0);
782 
783 	dev_info(DEV, "max_segment_size ( = BIO size ) = %u\n", queue_max_segment_size(q));
784 
785 	if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
786 		dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
787 		     q->backing_dev_info.ra_pages,
788 		     b->backing_dev_info.ra_pages);
789 		q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
790 	}
791 }
792 
793 /* serialize deconfig (worker exiting, doing cleanup)
794  * and reconfig (drbdsetup disk, drbdsetup net)
795  *
796  * Wait for a potentially exiting worker, then restart it,
797  * or start a new one.  Flush any pending work, there may still be an
798  * after_state_change queued.
799  */
800 static void drbd_reconfig_start(struct drbd_conf *mdev)
801 {
802 	wait_event(mdev->state_wait, !test_and_set_bit(CONFIG_PENDING, &mdev->flags));
803 	wait_event(mdev->state_wait, !test_bit(DEVICE_DYING, &mdev->flags));
804 	drbd_thread_start(&mdev->worker);
805 	drbd_flush_workqueue(mdev);
806 }
807 
808 /* if still unconfigured, stops worker again.
809  * if configured now, clears CONFIG_PENDING.
810  * wakes potential waiters */
811 static void drbd_reconfig_done(struct drbd_conf *mdev)
812 {
813 	spin_lock_irq(&mdev->req_lock);
814 	if (mdev->state.disk == D_DISKLESS &&
815 	    mdev->state.conn == C_STANDALONE &&
816 	    mdev->state.role == R_SECONDARY) {
817 		set_bit(DEVICE_DYING, &mdev->flags);
818 		drbd_thread_stop_nowait(&mdev->worker);
819 	} else
820 		clear_bit(CONFIG_PENDING, &mdev->flags);
821 	spin_unlock_irq(&mdev->req_lock);
822 	wake_up(&mdev->state_wait);
823 }
824 
825 /* Make sure IO is suspended before calling this function(). */
826 static void drbd_suspend_al(struct drbd_conf *mdev)
827 {
828 	int s = 0;
829 
830 	if (lc_try_lock(mdev->act_log)) {
831 		drbd_al_shrink(mdev);
832 		lc_unlock(mdev->act_log);
833 	} else {
834 		dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
835 		return;
836 	}
837 
838 	spin_lock_irq(&mdev->req_lock);
839 	if (mdev->state.conn < C_CONNECTED)
840 		s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
841 
842 	spin_unlock_irq(&mdev->req_lock);
843 
844 	if (s)
845 		dev_info(DEV, "Suspended AL updates\n");
846 }
847 
848 /* does always return 0;
849  * interesting return code is in reply->ret_code */
850 static int drbd_nl_disk_conf(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
851 			     struct drbd_nl_cfg_reply *reply)
852 {
853 	enum drbd_ret_codes retcode;
854 	enum determine_dev_size dd;
855 	sector_t max_possible_sectors;
856 	sector_t min_md_device_sectors;
857 	struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
858 	struct block_device *bdev;
859 	struct lru_cache *resync_lru = NULL;
860 	union drbd_state ns, os;
861 	unsigned int max_seg_s;
862 	int rv;
863 	int cp_discovered = 0;
864 	int logical_block_size;
865 
866 	drbd_reconfig_start(mdev);
867 
868 	/* if you want to reconfigure, please tear down first */
869 	if (mdev->state.disk > D_DISKLESS) {
870 		retcode = ERR_DISK_CONFIGURED;
871 		goto fail;
872 	}
873 	/* It may just now have detached because of IO error.  Make sure
874 	 * drbd_ldev_destroy is done already, we may end up here very fast,
875 	 * e.g. if someone calls attach from the on-io-error handler,
876 	 * to realize a "hot spare" feature (not that I'd recommend that) */
877 	wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
878 
879 	/* allocation not in the IO path, cqueue thread context */
880 	nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
881 	if (!nbc) {
882 		retcode = ERR_NOMEM;
883 		goto fail;
884 	}
885 
886 	nbc->dc.disk_size     = DRBD_DISK_SIZE_SECT_DEF;
887 	nbc->dc.on_io_error   = DRBD_ON_IO_ERROR_DEF;
888 	nbc->dc.fencing       = DRBD_FENCING_DEF;
889 	nbc->dc.max_bio_bvecs = DRBD_MAX_BIO_BVECS_DEF;
890 
891 	if (!disk_conf_from_tags(mdev, nlp->tag_list, &nbc->dc)) {
892 		retcode = ERR_MANDATORY_TAG;
893 		goto fail;
894 	}
895 
896 	if (nbc->dc.meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
897 		retcode = ERR_MD_IDX_INVALID;
898 		goto fail;
899 	}
900 
901 	if (get_net_conf(mdev)) {
902 		int prot = mdev->net_conf->wire_protocol;
903 		put_net_conf(mdev);
904 		if (nbc->dc.fencing == FP_STONITH && prot == DRBD_PROT_A) {
905 			retcode = ERR_STONITH_AND_PROT_A;
906 			goto fail;
907 		}
908 	}
909 
910 	bdev = blkdev_get_by_path(nbc->dc.backing_dev,
911 				  FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
912 	if (IS_ERR(bdev)) {
913 		dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.backing_dev,
914 			PTR_ERR(bdev));
915 		retcode = ERR_OPEN_DISK;
916 		goto fail;
917 	}
918 	nbc->backing_bdev = bdev;
919 
920 	/*
921 	 * meta_dev_idx >= 0: external fixed size, possibly multiple
922 	 * drbd sharing one meta device.  TODO in that case, paranoia
923 	 * check that [md_bdev, meta_dev_idx] is not yet used by some
924 	 * other drbd minor!  (if you use drbd.conf + drbdadm, that
925 	 * should check it for you already; but if you don't, or
926 	 * someone fooled it, we need to double check here)
927 	 */
928 	bdev = blkdev_get_by_path(nbc->dc.meta_dev,
929 				  FMODE_READ | FMODE_WRITE | FMODE_EXCL,
930 				  (nbc->dc.meta_dev_idx < 0) ?
931 				  (void *)mdev : (void *)drbd_m_holder);
932 	if (IS_ERR(bdev)) {
933 		dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.meta_dev,
934 			PTR_ERR(bdev));
935 		retcode = ERR_OPEN_MD_DISK;
936 		goto fail;
937 	}
938 	nbc->md_bdev = bdev;
939 
940 	if ((nbc->backing_bdev == nbc->md_bdev) !=
941 	    (nbc->dc.meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
942 	     nbc->dc.meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
943 		retcode = ERR_MD_IDX_INVALID;
944 		goto fail;
945 	}
946 
947 	resync_lru = lc_create("resync", drbd_bm_ext_cache,
948 			61, sizeof(struct bm_extent),
949 			offsetof(struct bm_extent, lce));
950 	if (!resync_lru) {
951 		retcode = ERR_NOMEM;
952 		goto fail;
953 	}
954 
955 	/* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
956 	drbd_md_set_sector_offsets(mdev, nbc);
957 
958 	if (drbd_get_max_capacity(nbc) < nbc->dc.disk_size) {
959 		dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
960 			(unsigned long long) drbd_get_max_capacity(nbc),
961 			(unsigned long long) nbc->dc.disk_size);
962 		retcode = ERR_DISK_TO_SMALL;
963 		goto fail;
964 	}
965 
966 	if (nbc->dc.meta_dev_idx < 0) {
967 		max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
968 		/* at least one MB, otherwise it does not make sense */
969 		min_md_device_sectors = (2<<10);
970 	} else {
971 		max_possible_sectors = DRBD_MAX_SECTORS;
972 		min_md_device_sectors = MD_RESERVED_SECT * (nbc->dc.meta_dev_idx + 1);
973 	}
974 
975 	if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
976 		retcode = ERR_MD_DISK_TO_SMALL;
977 		dev_warn(DEV, "refusing attach: md-device too small, "
978 		     "at least %llu sectors needed for this meta-disk type\n",
979 		     (unsigned long long) min_md_device_sectors);
980 		goto fail;
981 	}
982 
983 	/* Make sure the new disk is big enough
984 	 * (we may currently be R_PRIMARY with no local disk...) */
985 	if (drbd_get_max_capacity(nbc) <
986 	    drbd_get_capacity(mdev->this_bdev)) {
987 		retcode = ERR_DISK_TO_SMALL;
988 		goto fail;
989 	}
990 
991 	nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
992 
993 	if (nbc->known_size > max_possible_sectors) {
994 		dev_warn(DEV, "==> truncating very big lower level device "
995 			"to currently maximum possible %llu sectors <==\n",
996 			(unsigned long long) max_possible_sectors);
997 		if (nbc->dc.meta_dev_idx >= 0)
998 			dev_warn(DEV, "==>> using internal or flexible "
999 				      "meta data may help <<==\n");
1000 	}
1001 
1002 	drbd_suspend_io(mdev);
1003 	/* also wait for the last barrier ack. */
1004 	wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || is_susp(mdev->state));
1005 	/* and for any other previously queued work */
1006 	drbd_flush_workqueue(mdev);
1007 
1008 	retcode = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1009 	drbd_resume_io(mdev);
1010 	if (retcode < SS_SUCCESS)
1011 		goto fail;
1012 
1013 	if (!get_ldev_if_state(mdev, D_ATTACHING))
1014 		goto force_diskless;
1015 
1016 	drbd_md_set_sector_offsets(mdev, nbc);
1017 
1018 	/* allocate a second IO page if logical_block_size != 512 */
1019 	logical_block_size = bdev_logical_block_size(nbc->md_bdev);
1020 	if (logical_block_size == 0)
1021 		logical_block_size = MD_SECTOR_SIZE;
1022 
1023 	if (logical_block_size != MD_SECTOR_SIZE) {
1024 		if (!mdev->md_io_tmpp) {
1025 			struct page *page = alloc_page(GFP_NOIO);
1026 			if (!page)
1027 				goto force_diskless_dec;
1028 
1029 			dev_warn(DEV, "Meta data's bdev logical_block_size = %d != %d\n",
1030 			     logical_block_size, MD_SECTOR_SIZE);
1031 			dev_warn(DEV, "Workaround engaged (has performance impact).\n");
1032 
1033 			mdev->md_io_tmpp = page;
1034 		}
1035 	}
1036 
1037 	if (!mdev->bitmap) {
1038 		if (drbd_bm_init(mdev)) {
1039 			retcode = ERR_NOMEM;
1040 			goto force_diskless_dec;
1041 		}
1042 	}
1043 
1044 	retcode = drbd_md_read(mdev, nbc);
1045 	if (retcode != NO_ERROR)
1046 		goto force_diskless_dec;
1047 
1048 	if (mdev->state.conn < C_CONNECTED &&
1049 	    mdev->state.role == R_PRIMARY &&
1050 	    (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1051 		dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1052 		    (unsigned long long)mdev->ed_uuid);
1053 		retcode = ERR_DATA_NOT_CURRENT;
1054 		goto force_diskless_dec;
1055 	}
1056 
1057 	/* Since we are diskless, fix the activity log first... */
1058 	if (drbd_check_al_size(mdev)) {
1059 		retcode = ERR_NOMEM;
1060 		goto force_diskless_dec;
1061 	}
1062 
1063 	/* Prevent shrinking of consistent devices ! */
1064 	if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1065 	    drbd_new_dev_size(mdev, nbc, 0) < nbc->md.la_size_sect) {
1066 		dev_warn(DEV, "refusing to truncate a consistent device\n");
1067 		retcode = ERR_DISK_TO_SMALL;
1068 		goto force_diskless_dec;
1069 	}
1070 
1071 	if (!drbd_al_read_log(mdev, nbc)) {
1072 		retcode = ERR_IO_MD_DISK;
1073 		goto force_diskless_dec;
1074 	}
1075 
1076 	/* Reset the "barriers don't work" bits here, then force meta data to
1077 	 * be written, to ensure we determine if barriers are supported. */
1078 	if (nbc->dc.no_md_flush)
1079 		set_bit(MD_NO_FUA, &mdev->flags);
1080 	else
1081 		clear_bit(MD_NO_FUA, &mdev->flags);
1082 
1083 	/* Point of no return reached.
1084 	 * Devices and memory are no longer released by error cleanup below.
1085 	 * now mdev takes over responsibility, and the state engine should
1086 	 * clean it up somewhere.  */
1087 	D_ASSERT(mdev->ldev == NULL);
1088 	mdev->ldev = nbc;
1089 	mdev->resync = resync_lru;
1090 	nbc = NULL;
1091 	resync_lru = NULL;
1092 
1093 	mdev->write_ordering = WO_bdev_flush;
1094 	drbd_bump_write_ordering(mdev, WO_bdev_flush);
1095 
1096 	if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1097 		set_bit(CRASHED_PRIMARY, &mdev->flags);
1098 	else
1099 		clear_bit(CRASHED_PRIMARY, &mdev->flags);
1100 
1101 	if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1102 	    !(mdev->state.role == R_PRIMARY && mdev->state.susp_nod)) {
1103 		set_bit(CRASHED_PRIMARY, &mdev->flags);
1104 		cp_discovered = 1;
1105 	}
1106 
1107 	mdev->send_cnt = 0;
1108 	mdev->recv_cnt = 0;
1109 	mdev->read_cnt = 0;
1110 	mdev->writ_cnt = 0;
1111 
1112 	max_seg_s = DRBD_MAX_SEGMENT_SIZE;
1113 	if (mdev->state.conn == C_CONNECTED) {
1114 		/* We are Primary, Connected, and now attach a new local
1115 		 * backing store. We must not increase the user visible maximum
1116 		 * bio size on this device to something the peer may not be
1117 		 * able to handle. */
1118 		if (mdev->agreed_pro_version < 94)
1119 			max_seg_s = queue_max_segment_size(mdev->rq_queue);
1120 		else if (mdev->agreed_pro_version == 94)
1121 			max_seg_s = DRBD_MAX_SIZE_H80_PACKET;
1122 		/* else: drbd 8.3.9 and later, stay with default */
1123 	}
1124 
1125 	drbd_setup_queue_param(mdev, max_seg_s);
1126 
1127 	/* If I am currently not R_PRIMARY,
1128 	 * but meta data primary indicator is set,
1129 	 * I just now recover from a hard crash,
1130 	 * and have been R_PRIMARY before that crash.
1131 	 *
1132 	 * Now, if I had no connection before that crash
1133 	 * (have been degraded R_PRIMARY), chances are that
1134 	 * I won't find my peer now either.
1135 	 *
1136 	 * In that case, and _only_ in that case,
1137 	 * we use the degr-wfc-timeout instead of the default,
1138 	 * so we can automatically recover from a crash of a
1139 	 * degraded but active "cluster" after a certain timeout.
1140 	 */
1141 	clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1142 	if (mdev->state.role != R_PRIMARY &&
1143 	     drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1144 	    !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1145 		set_bit(USE_DEGR_WFC_T, &mdev->flags);
1146 
1147 	dd = drbd_determin_dev_size(mdev, 0);
1148 	if (dd == dev_size_error) {
1149 		retcode = ERR_NOMEM_BITMAP;
1150 		goto force_diskless_dec;
1151 	} else if (dd == grew)
1152 		set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1153 
1154 	if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1155 		dev_info(DEV, "Assuming that all blocks are out of sync "
1156 		     "(aka FullSync)\n");
1157 		if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write, "set_n_write from attaching")) {
1158 			retcode = ERR_IO_MD_DISK;
1159 			goto force_diskless_dec;
1160 		}
1161 	} else {
1162 		if (drbd_bitmap_io(mdev, &drbd_bm_read, "read from attaching") < 0) {
1163 			retcode = ERR_IO_MD_DISK;
1164 			goto force_diskless_dec;
1165 		}
1166 	}
1167 
1168 	if (cp_discovered) {
1169 		drbd_al_apply_to_bm(mdev);
1170 		drbd_al_to_on_disk_bm(mdev);
1171 	}
1172 
1173 	if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1174 		drbd_suspend_al(mdev); /* IO is still suspended here... */
1175 
1176 	spin_lock_irq(&mdev->req_lock);
1177 	os = mdev->state;
1178 	ns.i = os.i;
1179 	/* If MDF_CONSISTENT is not set go into inconsistent state,
1180 	   otherwise investigate MDF_WasUpToDate...
1181 	   If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1182 	   otherwise into D_CONSISTENT state.
1183 	*/
1184 	if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1185 		if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1186 			ns.disk = D_CONSISTENT;
1187 		else
1188 			ns.disk = D_OUTDATED;
1189 	} else {
1190 		ns.disk = D_INCONSISTENT;
1191 	}
1192 
1193 	if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1194 		ns.pdsk = D_OUTDATED;
1195 
1196 	if ( ns.disk == D_CONSISTENT &&
1197 	    (ns.pdsk == D_OUTDATED || mdev->ldev->dc.fencing == FP_DONT_CARE))
1198 		ns.disk = D_UP_TO_DATE;
1199 
1200 	/* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1201 	   MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1202 	   this point, because drbd_request_state() modifies these
1203 	   flags. */
1204 
1205 	/* In case we are C_CONNECTED postpone any decision on the new disk
1206 	   state after the negotiation phase. */
1207 	if (mdev->state.conn == C_CONNECTED) {
1208 		mdev->new_state_tmp.i = ns.i;
1209 		ns.i = os.i;
1210 		ns.disk = D_NEGOTIATING;
1211 
1212 		/* We expect to receive up-to-date UUIDs soon.
1213 		   To avoid a race in receive_state, free p_uuid while
1214 		   holding req_lock. I.e. atomic with the state change */
1215 		kfree(mdev->p_uuid);
1216 		mdev->p_uuid = NULL;
1217 	}
1218 
1219 	rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1220 	ns = mdev->state;
1221 	spin_unlock_irq(&mdev->req_lock);
1222 
1223 	if (rv < SS_SUCCESS)
1224 		goto force_diskless_dec;
1225 
1226 	if (mdev->state.role == R_PRIMARY)
1227 		mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1228 	else
1229 		mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1230 
1231 	drbd_md_mark_dirty(mdev);
1232 	drbd_md_sync(mdev);
1233 
1234 	kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1235 	put_ldev(mdev);
1236 	reply->ret_code = retcode;
1237 	drbd_reconfig_done(mdev);
1238 	return 0;
1239 
1240  force_diskless_dec:
1241 	put_ldev(mdev);
1242  force_diskless:
1243 	drbd_force_state(mdev, NS(disk, D_FAILED));
1244 	drbd_md_sync(mdev);
1245  fail:
1246 	if (nbc) {
1247 		if (nbc->backing_bdev)
1248 			blkdev_put(nbc->backing_bdev,
1249 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1250 		if (nbc->md_bdev)
1251 			blkdev_put(nbc->md_bdev,
1252 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1253 		kfree(nbc);
1254 	}
1255 	lc_destroy(resync_lru);
1256 
1257 	reply->ret_code = retcode;
1258 	drbd_reconfig_done(mdev);
1259 	return 0;
1260 }
1261 
1262 /* Detaching the disk is a process in multiple stages.  First we need to lock
1263  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1264  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1265  * internal references as well.
1266  * Only then we have finally detached. */
1267 static int drbd_nl_detach(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1268 			  struct drbd_nl_cfg_reply *reply)
1269 {
1270 	drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1271 	reply->ret_code = drbd_request_state(mdev, NS(disk, D_DISKLESS));
1272 	if (mdev->state.disk == D_DISKLESS)
1273 		wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1274 	drbd_resume_io(mdev);
1275 	return 0;
1276 }
1277 
1278 static int drbd_nl_net_conf(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1279 			    struct drbd_nl_cfg_reply *reply)
1280 {
1281 	int i, ns;
1282 	enum drbd_ret_codes retcode;
1283 	struct net_conf *new_conf = NULL;
1284 	struct crypto_hash *tfm = NULL;
1285 	struct crypto_hash *integrity_w_tfm = NULL;
1286 	struct crypto_hash *integrity_r_tfm = NULL;
1287 	struct hlist_head *new_tl_hash = NULL;
1288 	struct hlist_head *new_ee_hash = NULL;
1289 	struct drbd_conf *odev;
1290 	char hmac_name[CRYPTO_MAX_ALG_NAME];
1291 	void *int_dig_out = NULL;
1292 	void *int_dig_in = NULL;
1293 	void *int_dig_vv = NULL;
1294 	struct sockaddr *new_my_addr, *new_peer_addr, *taken_addr;
1295 
1296 	drbd_reconfig_start(mdev);
1297 
1298 	if (mdev->state.conn > C_STANDALONE) {
1299 		retcode = ERR_NET_CONFIGURED;
1300 		goto fail;
1301 	}
1302 
1303 	/* allocation not in the IO path, cqueue thread context */
1304 	new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1305 	if (!new_conf) {
1306 		retcode = ERR_NOMEM;
1307 		goto fail;
1308 	}
1309 
1310 	new_conf->timeout	   = DRBD_TIMEOUT_DEF;
1311 	new_conf->try_connect_int  = DRBD_CONNECT_INT_DEF;
1312 	new_conf->ping_int	   = DRBD_PING_INT_DEF;
1313 	new_conf->max_epoch_size   = DRBD_MAX_EPOCH_SIZE_DEF;
1314 	new_conf->max_buffers	   = DRBD_MAX_BUFFERS_DEF;
1315 	new_conf->unplug_watermark = DRBD_UNPLUG_WATERMARK_DEF;
1316 	new_conf->sndbuf_size	   = DRBD_SNDBUF_SIZE_DEF;
1317 	new_conf->rcvbuf_size	   = DRBD_RCVBUF_SIZE_DEF;
1318 	new_conf->ko_count	   = DRBD_KO_COUNT_DEF;
1319 	new_conf->after_sb_0p	   = DRBD_AFTER_SB_0P_DEF;
1320 	new_conf->after_sb_1p	   = DRBD_AFTER_SB_1P_DEF;
1321 	new_conf->after_sb_2p	   = DRBD_AFTER_SB_2P_DEF;
1322 	new_conf->want_lose	   = 0;
1323 	new_conf->two_primaries    = 0;
1324 	new_conf->wire_protocol    = DRBD_PROT_C;
1325 	new_conf->ping_timeo	   = DRBD_PING_TIMEO_DEF;
1326 	new_conf->rr_conflict	   = DRBD_RR_CONFLICT_DEF;
1327 
1328 	if (!net_conf_from_tags(mdev, nlp->tag_list, new_conf)) {
1329 		retcode = ERR_MANDATORY_TAG;
1330 		goto fail;
1331 	}
1332 
1333 	if (new_conf->two_primaries
1334 	    && (new_conf->wire_protocol != DRBD_PROT_C)) {
1335 		retcode = ERR_NOT_PROTO_C;
1336 		goto fail;
1337 	}
1338 
1339 	if (get_ldev(mdev)) {
1340 		enum drbd_fencing_p fp = mdev->ldev->dc.fencing;
1341 		put_ldev(mdev);
1342 		if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH) {
1343 			retcode = ERR_STONITH_AND_PROT_A;
1344 			goto fail;
1345 		}
1346 	}
1347 
1348 	if (mdev->state.role == R_PRIMARY && new_conf->want_lose) {
1349 		retcode = ERR_DISCARD;
1350 		goto fail;
1351 	}
1352 
1353 	retcode = NO_ERROR;
1354 
1355 	new_my_addr = (struct sockaddr *)&new_conf->my_addr;
1356 	new_peer_addr = (struct sockaddr *)&new_conf->peer_addr;
1357 	for (i = 0; i < minor_count; i++) {
1358 		odev = minor_to_mdev(i);
1359 		if (!odev || odev == mdev)
1360 			continue;
1361 		if (get_net_conf(odev)) {
1362 			taken_addr = (struct sockaddr *)&odev->net_conf->my_addr;
1363 			if (new_conf->my_addr_len == odev->net_conf->my_addr_len &&
1364 			    !memcmp(new_my_addr, taken_addr, new_conf->my_addr_len))
1365 				retcode = ERR_LOCAL_ADDR;
1366 
1367 			taken_addr = (struct sockaddr *)&odev->net_conf->peer_addr;
1368 			if (new_conf->peer_addr_len == odev->net_conf->peer_addr_len &&
1369 			    !memcmp(new_peer_addr, taken_addr, new_conf->peer_addr_len))
1370 				retcode = ERR_PEER_ADDR;
1371 
1372 			put_net_conf(odev);
1373 			if (retcode != NO_ERROR)
1374 				goto fail;
1375 		}
1376 	}
1377 
1378 	if (new_conf->cram_hmac_alg[0] != 0) {
1379 		snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1380 			new_conf->cram_hmac_alg);
1381 		tfm = crypto_alloc_hash(hmac_name, 0, CRYPTO_ALG_ASYNC);
1382 		if (IS_ERR(tfm)) {
1383 			tfm = NULL;
1384 			retcode = ERR_AUTH_ALG;
1385 			goto fail;
1386 		}
1387 
1388 		if (!drbd_crypto_is_hash(crypto_hash_tfm(tfm))) {
1389 			retcode = ERR_AUTH_ALG_ND;
1390 			goto fail;
1391 		}
1392 	}
1393 
1394 	if (new_conf->integrity_alg[0]) {
1395 		integrity_w_tfm = crypto_alloc_hash(new_conf->integrity_alg, 0, CRYPTO_ALG_ASYNC);
1396 		if (IS_ERR(integrity_w_tfm)) {
1397 			integrity_w_tfm = NULL;
1398 			retcode=ERR_INTEGRITY_ALG;
1399 			goto fail;
1400 		}
1401 
1402 		if (!drbd_crypto_is_hash(crypto_hash_tfm(integrity_w_tfm))) {
1403 			retcode=ERR_INTEGRITY_ALG_ND;
1404 			goto fail;
1405 		}
1406 
1407 		integrity_r_tfm = crypto_alloc_hash(new_conf->integrity_alg, 0, CRYPTO_ALG_ASYNC);
1408 		if (IS_ERR(integrity_r_tfm)) {
1409 			integrity_r_tfm = NULL;
1410 			retcode=ERR_INTEGRITY_ALG;
1411 			goto fail;
1412 		}
1413 	}
1414 
1415 	ns = new_conf->max_epoch_size/8;
1416 	if (mdev->tl_hash_s != ns) {
1417 		new_tl_hash = kzalloc(ns*sizeof(void *), GFP_KERNEL);
1418 		if (!new_tl_hash) {
1419 			retcode = ERR_NOMEM;
1420 			goto fail;
1421 		}
1422 	}
1423 
1424 	ns = new_conf->max_buffers/8;
1425 	if (new_conf->two_primaries && (mdev->ee_hash_s != ns)) {
1426 		new_ee_hash = kzalloc(ns*sizeof(void *), GFP_KERNEL);
1427 		if (!new_ee_hash) {
1428 			retcode = ERR_NOMEM;
1429 			goto fail;
1430 		}
1431 	}
1432 
1433 	((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
1434 
1435 	if (integrity_w_tfm) {
1436 		i = crypto_hash_digestsize(integrity_w_tfm);
1437 		int_dig_out = kmalloc(i, GFP_KERNEL);
1438 		if (!int_dig_out) {
1439 			retcode = ERR_NOMEM;
1440 			goto fail;
1441 		}
1442 		int_dig_in = kmalloc(i, GFP_KERNEL);
1443 		if (!int_dig_in) {
1444 			retcode = ERR_NOMEM;
1445 			goto fail;
1446 		}
1447 		int_dig_vv = kmalloc(i, GFP_KERNEL);
1448 		if (!int_dig_vv) {
1449 			retcode = ERR_NOMEM;
1450 			goto fail;
1451 		}
1452 	}
1453 
1454 	if (!mdev->bitmap) {
1455 		if(drbd_bm_init(mdev)) {
1456 			retcode = ERR_NOMEM;
1457 			goto fail;
1458 		}
1459 	}
1460 
1461 	drbd_flush_workqueue(mdev);
1462 	spin_lock_irq(&mdev->req_lock);
1463 	if (mdev->net_conf != NULL) {
1464 		retcode = ERR_NET_CONFIGURED;
1465 		spin_unlock_irq(&mdev->req_lock);
1466 		goto fail;
1467 	}
1468 	mdev->net_conf = new_conf;
1469 
1470 	mdev->send_cnt = 0;
1471 	mdev->recv_cnt = 0;
1472 
1473 	if (new_tl_hash) {
1474 		kfree(mdev->tl_hash);
1475 		mdev->tl_hash_s = mdev->net_conf->max_epoch_size/8;
1476 		mdev->tl_hash = new_tl_hash;
1477 	}
1478 
1479 	if (new_ee_hash) {
1480 		kfree(mdev->ee_hash);
1481 		mdev->ee_hash_s = mdev->net_conf->max_buffers/8;
1482 		mdev->ee_hash = new_ee_hash;
1483 	}
1484 
1485 	crypto_free_hash(mdev->cram_hmac_tfm);
1486 	mdev->cram_hmac_tfm = tfm;
1487 
1488 	crypto_free_hash(mdev->integrity_w_tfm);
1489 	mdev->integrity_w_tfm = integrity_w_tfm;
1490 
1491 	crypto_free_hash(mdev->integrity_r_tfm);
1492 	mdev->integrity_r_tfm = integrity_r_tfm;
1493 
1494 	kfree(mdev->int_dig_out);
1495 	kfree(mdev->int_dig_in);
1496 	kfree(mdev->int_dig_vv);
1497 	mdev->int_dig_out=int_dig_out;
1498 	mdev->int_dig_in=int_dig_in;
1499 	mdev->int_dig_vv=int_dig_vv;
1500 	retcode = _drbd_set_state(_NS(mdev, conn, C_UNCONNECTED), CS_VERBOSE, NULL);
1501 	spin_unlock_irq(&mdev->req_lock);
1502 
1503 	kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1504 	reply->ret_code = retcode;
1505 	drbd_reconfig_done(mdev);
1506 	return 0;
1507 
1508 fail:
1509 	kfree(int_dig_out);
1510 	kfree(int_dig_in);
1511 	kfree(int_dig_vv);
1512 	crypto_free_hash(tfm);
1513 	crypto_free_hash(integrity_w_tfm);
1514 	crypto_free_hash(integrity_r_tfm);
1515 	kfree(new_tl_hash);
1516 	kfree(new_ee_hash);
1517 	kfree(new_conf);
1518 
1519 	reply->ret_code = retcode;
1520 	drbd_reconfig_done(mdev);
1521 	return 0;
1522 }
1523 
1524 static int drbd_nl_disconnect(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1525 			      struct drbd_nl_cfg_reply *reply)
1526 {
1527 	int retcode;
1528 
1529 	retcode = _drbd_request_state(mdev, NS(conn, C_DISCONNECTING), CS_ORDERED);
1530 
1531 	if (retcode == SS_NOTHING_TO_DO)
1532 		goto done;
1533 	else if (retcode == SS_ALREADY_STANDALONE)
1534 		goto done;
1535 	else if (retcode == SS_PRIMARY_NOP) {
1536 		/* Our statche checking code wants to see the peer outdated. */
1537 		retcode = drbd_request_state(mdev, NS2(conn, C_DISCONNECTING,
1538 						      pdsk, D_OUTDATED));
1539 	} else if (retcode == SS_CW_FAILED_BY_PEER) {
1540 		/* The peer probably wants to see us outdated. */
1541 		retcode = _drbd_request_state(mdev, NS2(conn, C_DISCONNECTING,
1542 							disk, D_OUTDATED),
1543 					      CS_ORDERED);
1544 		if (retcode == SS_IS_DISKLESS || retcode == SS_LOWER_THAN_OUTDATED) {
1545 			drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
1546 			retcode = SS_SUCCESS;
1547 		}
1548 	}
1549 
1550 	if (retcode < SS_SUCCESS)
1551 		goto fail;
1552 
1553 	if (wait_event_interruptible(mdev->state_wait,
1554 				     mdev->state.conn != C_DISCONNECTING)) {
1555 		/* Do not test for mdev->state.conn == C_STANDALONE, since
1556 		   someone else might connect us in the mean time! */
1557 		retcode = ERR_INTR;
1558 		goto fail;
1559 	}
1560 
1561  done:
1562 	retcode = NO_ERROR;
1563  fail:
1564 	drbd_md_sync(mdev);
1565 	reply->ret_code = retcode;
1566 	return 0;
1567 }
1568 
1569 void resync_after_online_grow(struct drbd_conf *mdev)
1570 {
1571 	int iass; /* I am sync source */
1572 
1573 	dev_info(DEV, "Resync of new storage after online grow\n");
1574 	if (mdev->state.role != mdev->state.peer)
1575 		iass = (mdev->state.role == R_PRIMARY);
1576 	else
1577 		iass = test_bit(DISCARD_CONCURRENT, &mdev->flags);
1578 
1579 	if (iass)
1580 		drbd_start_resync(mdev, C_SYNC_SOURCE);
1581 	else
1582 		_drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
1583 }
1584 
1585 static int drbd_nl_resize(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1586 			  struct drbd_nl_cfg_reply *reply)
1587 {
1588 	struct resize rs;
1589 	int retcode = NO_ERROR;
1590 	enum determine_dev_size dd;
1591 	enum dds_flags ddsf;
1592 
1593 	memset(&rs, 0, sizeof(struct resize));
1594 	if (!resize_from_tags(mdev, nlp->tag_list, &rs)) {
1595 		retcode = ERR_MANDATORY_TAG;
1596 		goto fail;
1597 	}
1598 
1599 	if (mdev->state.conn > C_CONNECTED) {
1600 		retcode = ERR_RESIZE_RESYNC;
1601 		goto fail;
1602 	}
1603 
1604 	if (mdev->state.role == R_SECONDARY &&
1605 	    mdev->state.peer == R_SECONDARY) {
1606 		retcode = ERR_NO_PRIMARY;
1607 		goto fail;
1608 	}
1609 
1610 	if (!get_ldev(mdev)) {
1611 		retcode = ERR_NO_DISK;
1612 		goto fail;
1613 	}
1614 
1615 	if (rs.no_resync && mdev->agreed_pro_version < 93) {
1616 		retcode = ERR_NEED_APV_93;
1617 		goto fail;
1618 	}
1619 
1620 	if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
1621 		mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
1622 
1623 	mdev->ldev->dc.disk_size = (sector_t)rs.resize_size;
1624 	ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
1625 	dd = drbd_determin_dev_size(mdev, ddsf);
1626 	drbd_md_sync(mdev);
1627 	put_ldev(mdev);
1628 	if (dd == dev_size_error) {
1629 		retcode = ERR_NOMEM_BITMAP;
1630 		goto fail;
1631 	}
1632 
1633 	if (mdev->state.conn == C_CONNECTED) {
1634 		if (dd == grew)
1635 			set_bit(RESIZE_PENDING, &mdev->flags);
1636 
1637 		drbd_send_uuids(mdev);
1638 		drbd_send_sizes(mdev, 1, ddsf);
1639 	}
1640 
1641  fail:
1642 	reply->ret_code = retcode;
1643 	return 0;
1644 }
1645 
1646 static int drbd_nl_syncer_conf(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1647 			       struct drbd_nl_cfg_reply *reply)
1648 {
1649 	int retcode = NO_ERROR;
1650 	int err;
1651 	int ovr; /* online verify running */
1652 	int rsr; /* re-sync running */
1653 	struct crypto_hash *verify_tfm = NULL;
1654 	struct crypto_hash *csums_tfm = NULL;
1655 	struct syncer_conf sc;
1656 	cpumask_var_t new_cpu_mask;
1657 	int *rs_plan_s = NULL;
1658 	int fifo_size;
1659 
1660 	if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) {
1661 		retcode = ERR_NOMEM;
1662 		goto fail;
1663 	}
1664 
1665 	if (nlp->flags & DRBD_NL_SET_DEFAULTS) {
1666 		memset(&sc, 0, sizeof(struct syncer_conf));
1667 		sc.rate       = DRBD_RATE_DEF;
1668 		sc.after      = DRBD_AFTER_DEF;
1669 		sc.al_extents = DRBD_AL_EXTENTS_DEF;
1670 		sc.on_no_data  = DRBD_ON_NO_DATA_DEF;
1671 		sc.c_plan_ahead = DRBD_C_PLAN_AHEAD_DEF;
1672 		sc.c_delay_target = DRBD_C_DELAY_TARGET_DEF;
1673 		sc.c_fill_target = DRBD_C_FILL_TARGET_DEF;
1674 		sc.c_max_rate = DRBD_C_MAX_RATE_DEF;
1675 		sc.c_min_rate = DRBD_C_MIN_RATE_DEF;
1676 	} else
1677 		memcpy(&sc, &mdev->sync_conf, sizeof(struct syncer_conf));
1678 
1679 	if (!syncer_conf_from_tags(mdev, nlp->tag_list, &sc)) {
1680 		retcode = ERR_MANDATORY_TAG;
1681 		goto fail;
1682 	}
1683 
1684 	/* re-sync running */
1685 	rsr = (	mdev->state.conn == C_SYNC_SOURCE ||
1686 		mdev->state.conn == C_SYNC_TARGET ||
1687 		mdev->state.conn == C_PAUSED_SYNC_S ||
1688 		mdev->state.conn == C_PAUSED_SYNC_T );
1689 
1690 	if (rsr && strcmp(sc.csums_alg, mdev->sync_conf.csums_alg)) {
1691 		retcode = ERR_CSUMS_RESYNC_RUNNING;
1692 		goto fail;
1693 	}
1694 
1695 	if (!rsr && sc.csums_alg[0]) {
1696 		csums_tfm = crypto_alloc_hash(sc.csums_alg, 0, CRYPTO_ALG_ASYNC);
1697 		if (IS_ERR(csums_tfm)) {
1698 			csums_tfm = NULL;
1699 			retcode = ERR_CSUMS_ALG;
1700 			goto fail;
1701 		}
1702 
1703 		if (!drbd_crypto_is_hash(crypto_hash_tfm(csums_tfm))) {
1704 			retcode = ERR_CSUMS_ALG_ND;
1705 			goto fail;
1706 		}
1707 	}
1708 
1709 	/* online verify running */
1710 	ovr = (mdev->state.conn == C_VERIFY_S || mdev->state.conn == C_VERIFY_T);
1711 
1712 	if (ovr) {
1713 		if (strcmp(sc.verify_alg, mdev->sync_conf.verify_alg)) {
1714 			retcode = ERR_VERIFY_RUNNING;
1715 			goto fail;
1716 		}
1717 	}
1718 
1719 	if (!ovr && sc.verify_alg[0]) {
1720 		verify_tfm = crypto_alloc_hash(sc.verify_alg, 0, CRYPTO_ALG_ASYNC);
1721 		if (IS_ERR(verify_tfm)) {
1722 			verify_tfm = NULL;
1723 			retcode = ERR_VERIFY_ALG;
1724 			goto fail;
1725 		}
1726 
1727 		if (!drbd_crypto_is_hash(crypto_hash_tfm(verify_tfm))) {
1728 			retcode = ERR_VERIFY_ALG_ND;
1729 			goto fail;
1730 		}
1731 	}
1732 
1733 	/* silently ignore cpu mask on UP kernel */
1734 	if (nr_cpu_ids > 1 && sc.cpu_mask[0] != 0) {
1735 		err = __bitmap_parse(sc.cpu_mask, 32, 0,
1736 				cpumask_bits(new_cpu_mask), nr_cpu_ids);
1737 		if (err) {
1738 			dev_warn(DEV, "__bitmap_parse() failed with %d\n", err);
1739 			retcode = ERR_CPU_MASK_PARSE;
1740 			goto fail;
1741 		}
1742 	}
1743 
1744 	ERR_IF (sc.rate < 1) sc.rate = 1;
1745 	ERR_IF (sc.al_extents < 7) sc.al_extents = 127; /* arbitrary minimum */
1746 #define AL_MAX ((MD_AL_MAX_SIZE-1) * AL_EXTENTS_PT)
1747 	if (sc.al_extents > AL_MAX) {
1748 		dev_err(DEV, "sc.al_extents > %d\n", AL_MAX);
1749 		sc.al_extents = AL_MAX;
1750 	}
1751 #undef AL_MAX
1752 
1753 	/* to avoid spurious errors when configuring minors before configuring
1754 	 * the minors they depend on: if necessary, first create the minor we
1755 	 * depend on */
1756 	if (sc.after >= 0)
1757 		ensure_mdev(sc.after, 1);
1758 
1759 	/* most sanity checks done, try to assign the new sync-after
1760 	 * dependency.  need to hold the global lock in there,
1761 	 * to avoid a race in the dependency loop check. */
1762 	retcode = drbd_alter_sa(mdev, sc.after);
1763 	if (retcode != NO_ERROR)
1764 		goto fail;
1765 
1766 	fifo_size = (sc.c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1767 	if (fifo_size != mdev->rs_plan_s.size && fifo_size > 0) {
1768 		rs_plan_s   = kzalloc(sizeof(int) * fifo_size, GFP_KERNEL);
1769 		if (!rs_plan_s) {
1770 			dev_err(DEV, "kmalloc of fifo_buffer failed");
1771 			retcode = ERR_NOMEM;
1772 			goto fail;
1773 		}
1774 	}
1775 
1776 	/* ok, assign the rest of it as well.
1777 	 * lock against receive_SyncParam() */
1778 	spin_lock(&mdev->peer_seq_lock);
1779 	mdev->sync_conf = sc;
1780 
1781 	if (!rsr) {
1782 		crypto_free_hash(mdev->csums_tfm);
1783 		mdev->csums_tfm = csums_tfm;
1784 		csums_tfm = NULL;
1785 	}
1786 
1787 	if (!ovr) {
1788 		crypto_free_hash(mdev->verify_tfm);
1789 		mdev->verify_tfm = verify_tfm;
1790 		verify_tfm = NULL;
1791 	}
1792 
1793 	if (fifo_size != mdev->rs_plan_s.size) {
1794 		kfree(mdev->rs_plan_s.values);
1795 		mdev->rs_plan_s.values = rs_plan_s;
1796 		mdev->rs_plan_s.size   = fifo_size;
1797 		mdev->rs_planed = 0;
1798 		rs_plan_s = NULL;
1799 	}
1800 
1801 	spin_unlock(&mdev->peer_seq_lock);
1802 
1803 	if (get_ldev(mdev)) {
1804 		wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1805 		drbd_al_shrink(mdev);
1806 		err = drbd_check_al_size(mdev);
1807 		lc_unlock(mdev->act_log);
1808 		wake_up(&mdev->al_wait);
1809 
1810 		put_ldev(mdev);
1811 		drbd_md_sync(mdev);
1812 
1813 		if (err) {
1814 			retcode = ERR_NOMEM;
1815 			goto fail;
1816 		}
1817 	}
1818 
1819 	if (mdev->state.conn >= C_CONNECTED)
1820 		drbd_send_sync_param(mdev, &sc);
1821 
1822 	if (!cpumask_equal(mdev->cpu_mask, new_cpu_mask)) {
1823 		cpumask_copy(mdev->cpu_mask, new_cpu_mask);
1824 		drbd_calc_cpu_mask(mdev);
1825 		mdev->receiver.reset_cpu_mask = 1;
1826 		mdev->asender.reset_cpu_mask = 1;
1827 		mdev->worker.reset_cpu_mask = 1;
1828 	}
1829 
1830 	kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1831 fail:
1832 	kfree(rs_plan_s);
1833 	free_cpumask_var(new_cpu_mask);
1834 	crypto_free_hash(csums_tfm);
1835 	crypto_free_hash(verify_tfm);
1836 	reply->ret_code = retcode;
1837 	return 0;
1838 }
1839 
1840 static int drbd_nl_invalidate(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1841 			      struct drbd_nl_cfg_reply *reply)
1842 {
1843 	int retcode;
1844 
1845 	retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
1846 
1847 	if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
1848 		retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
1849 
1850 	while (retcode == SS_NEED_CONNECTION) {
1851 		spin_lock_irq(&mdev->req_lock);
1852 		if (mdev->state.conn < C_CONNECTED)
1853 			retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
1854 		spin_unlock_irq(&mdev->req_lock);
1855 
1856 		if (retcode != SS_NEED_CONNECTION)
1857 			break;
1858 
1859 		retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
1860 	}
1861 
1862 	reply->ret_code = retcode;
1863 	return 0;
1864 }
1865 
1866 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
1867 {
1868 	int rv;
1869 
1870 	rv = drbd_bmio_set_n_write(mdev);
1871 	drbd_suspend_al(mdev);
1872 	return rv;
1873 }
1874 
1875 static int drbd_nl_invalidate_peer(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1876 				   struct drbd_nl_cfg_reply *reply)
1877 {
1878 	int retcode;
1879 
1880 	retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S), CS_ORDERED);
1881 
1882 	if (retcode < SS_SUCCESS) {
1883 		if (retcode == SS_NEED_CONNECTION && mdev->state.role == R_PRIMARY) {
1884 			/* The peer will get a resync upon connect anyways. Just make that
1885 			   into a full resync. */
1886 			retcode = drbd_request_state(mdev, NS(pdsk, D_INCONSISTENT));
1887 			if (retcode >= SS_SUCCESS) {
1888 				/* open coded drbd_bitmap_io() */
1889 				if (drbd_bitmap_io(mdev, &drbd_bmio_set_susp_al,
1890 						   "set_n_write from invalidate_peer"))
1891 					retcode = ERR_IO_MD_DISK;
1892 			}
1893 		} else
1894 			retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S));
1895 	}
1896 
1897 	reply->ret_code = retcode;
1898 	return 0;
1899 }
1900 
1901 static int drbd_nl_pause_sync(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1902 			      struct drbd_nl_cfg_reply *reply)
1903 {
1904 	int retcode = NO_ERROR;
1905 
1906 	if (drbd_request_state(mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
1907 		retcode = ERR_PAUSE_IS_SET;
1908 
1909 	reply->ret_code = retcode;
1910 	return 0;
1911 }
1912 
1913 static int drbd_nl_resume_sync(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1914 			       struct drbd_nl_cfg_reply *reply)
1915 {
1916 	int retcode = NO_ERROR;
1917 
1918 	if (drbd_request_state(mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO)
1919 		retcode = ERR_PAUSE_IS_CLEAR;
1920 
1921 	reply->ret_code = retcode;
1922 	return 0;
1923 }
1924 
1925 static int drbd_nl_suspend_io(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1926 			      struct drbd_nl_cfg_reply *reply)
1927 {
1928 	reply->ret_code = drbd_request_state(mdev, NS(susp, 1));
1929 
1930 	return 0;
1931 }
1932 
1933 static int drbd_nl_resume_io(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1934 			     struct drbd_nl_cfg_reply *reply)
1935 {
1936 	if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
1937 		drbd_uuid_new_current(mdev);
1938 		clear_bit(NEW_CUR_UUID, &mdev->flags);
1939 	}
1940 	drbd_suspend_io(mdev);
1941 	reply->ret_code = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
1942 	if (reply->ret_code == SS_SUCCESS) {
1943 		if (mdev->state.conn < C_CONNECTED)
1944 			tl_clear(mdev);
1945 		if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
1946 			tl_restart(mdev, fail_frozen_disk_io);
1947 	}
1948 	drbd_resume_io(mdev);
1949 
1950 	return 0;
1951 }
1952 
1953 static int drbd_nl_outdate(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1954 			   struct drbd_nl_cfg_reply *reply)
1955 {
1956 	reply->ret_code = drbd_request_state(mdev, NS(disk, D_OUTDATED));
1957 	return 0;
1958 }
1959 
1960 static int drbd_nl_get_config(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1961 			   struct drbd_nl_cfg_reply *reply)
1962 {
1963 	unsigned short *tl;
1964 
1965 	tl = reply->tag_list;
1966 
1967 	if (get_ldev(mdev)) {
1968 		tl = disk_conf_to_tags(mdev, &mdev->ldev->dc, tl);
1969 		put_ldev(mdev);
1970 	}
1971 
1972 	if (get_net_conf(mdev)) {
1973 		tl = net_conf_to_tags(mdev, mdev->net_conf, tl);
1974 		put_net_conf(mdev);
1975 	}
1976 	tl = syncer_conf_to_tags(mdev, &mdev->sync_conf, tl);
1977 
1978 	put_unaligned(TT_END, tl++); /* Close the tag list */
1979 
1980 	return (int)((char *)tl - (char *)reply->tag_list);
1981 }
1982 
1983 static int drbd_nl_get_state(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
1984 			     struct drbd_nl_cfg_reply *reply)
1985 {
1986 	unsigned short *tl = reply->tag_list;
1987 	union drbd_state s = mdev->state;
1988 	unsigned long rs_left;
1989 	unsigned int res;
1990 
1991 	tl = get_state_to_tags(mdev, (struct get_state *)&s, tl);
1992 
1993 	/* no local ref, no bitmap, no syncer progress. */
1994 	if (s.conn >= C_SYNC_SOURCE && s.conn <= C_PAUSED_SYNC_T) {
1995 		if (get_ldev(mdev)) {
1996 			drbd_get_syncer_progress(mdev, &rs_left, &res);
1997 			tl = tl_add_int(tl, T_sync_progress, &res);
1998 			put_ldev(mdev);
1999 		}
2000 	}
2001 	put_unaligned(TT_END, tl++); /* Close the tag list */
2002 
2003 	return (int)((char *)tl - (char *)reply->tag_list);
2004 }
2005 
2006 static int drbd_nl_get_uuids(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
2007 			     struct drbd_nl_cfg_reply *reply)
2008 {
2009 	unsigned short *tl;
2010 
2011 	tl = reply->tag_list;
2012 
2013 	if (get_ldev(mdev)) {
2014 		tl = tl_add_blob(tl, T_uuids, mdev->ldev->md.uuid, UI_SIZE*sizeof(u64));
2015 		tl = tl_add_int(tl, T_uuids_flags, &mdev->ldev->md.flags);
2016 		put_ldev(mdev);
2017 	}
2018 	put_unaligned(TT_END, tl++); /* Close the tag list */
2019 
2020 	return (int)((char *)tl - (char *)reply->tag_list);
2021 }
2022 
2023 /**
2024  * drbd_nl_get_timeout_flag() - Used by drbdsetup to find out which timeout value to use
2025  * @mdev:	DRBD device.
2026  * @nlp:	Netlink/connector packet from drbdsetup
2027  * @reply:	Reply packet for drbdsetup
2028  */
2029 static int drbd_nl_get_timeout_flag(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
2030 				    struct drbd_nl_cfg_reply *reply)
2031 {
2032 	unsigned short *tl;
2033 	char rv;
2034 
2035 	tl = reply->tag_list;
2036 
2037 	rv = mdev->state.pdsk == D_OUTDATED        ? UT_PEER_OUTDATED :
2038 	  test_bit(USE_DEGR_WFC_T, &mdev->flags) ? UT_DEGRADED : UT_DEFAULT;
2039 
2040 	tl = tl_add_blob(tl, T_use_degraded, &rv, sizeof(rv));
2041 	put_unaligned(TT_END, tl++); /* Close the tag list */
2042 
2043 	return (int)((char *)tl - (char *)reply->tag_list);
2044 }
2045 
2046 static int drbd_nl_start_ov(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
2047 				    struct drbd_nl_cfg_reply *reply)
2048 {
2049 	/* default to resume from last known position, if possible */
2050 	struct start_ov args =
2051 		{ .start_sector = mdev->ov_start_sector };
2052 
2053 	if (!start_ov_from_tags(mdev, nlp->tag_list, &args)) {
2054 		reply->ret_code = ERR_MANDATORY_TAG;
2055 		return 0;
2056 	}
2057 	/* w_make_ov_request expects position to be aligned */
2058 	mdev->ov_start_sector = args.start_sector & ~BM_SECT_PER_BIT;
2059 	reply->ret_code = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2060 	return 0;
2061 }
2062 
2063 
2064 static int drbd_nl_new_c_uuid(struct drbd_conf *mdev, struct drbd_nl_cfg_req *nlp,
2065 			      struct drbd_nl_cfg_reply *reply)
2066 {
2067 	int retcode = NO_ERROR;
2068 	int skip_initial_sync = 0;
2069 	int err;
2070 
2071 	struct new_c_uuid args;
2072 
2073 	memset(&args, 0, sizeof(struct new_c_uuid));
2074 	if (!new_c_uuid_from_tags(mdev, nlp->tag_list, &args)) {
2075 		reply->ret_code = ERR_MANDATORY_TAG;
2076 		return 0;
2077 	}
2078 
2079 	mutex_lock(&mdev->state_mutex); /* Protects us against serialized state changes. */
2080 
2081 	if (!get_ldev(mdev)) {
2082 		retcode = ERR_NO_DISK;
2083 		goto out;
2084 	}
2085 
2086 	/* this is "skip initial sync", assume to be clean */
2087 	if (mdev->state.conn == C_CONNECTED && mdev->agreed_pro_version >= 90 &&
2088 	    mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2089 		dev_info(DEV, "Preparing to skip initial sync\n");
2090 		skip_initial_sync = 1;
2091 	} else if (mdev->state.conn != C_STANDALONE) {
2092 		retcode = ERR_CONNECTED;
2093 		goto out_dec;
2094 	}
2095 
2096 	drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2097 	drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2098 
2099 	if (args.clear_bm) {
2100 		err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write, "clear_n_write from new_c_uuid");
2101 		if (err) {
2102 			dev_err(DEV, "Writing bitmap failed with %d\n",err);
2103 			retcode = ERR_IO_MD_DISK;
2104 		}
2105 		if (skip_initial_sync) {
2106 			drbd_send_uuids_skip_initial_sync(mdev);
2107 			_drbd_uuid_set(mdev, UI_BITMAP, 0);
2108 			spin_lock_irq(&mdev->req_lock);
2109 			_drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2110 					CS_VERBOSE, NULL);
2111 			spin_unlock_irq(&mdev->req_lock);
2112 		}
2113 	}
2114 
2115 	drbd_md_sync(mdev);
2116 out_dec:
2117 	put_ldev(mdev);
2118 out:
2119 	mutex_unlock(&mdev->state_mutex);
2120 
2121 	reply->ret_code = retcode;
2122 	return 0;
2123 }
2124 
2125 struct cn_handler_struct {
2126 	int (*function)(struct drbd_conf *,
2127 			 struct drbd_nl_cfg_req *,
2128 			 struct drbd_nl_cfg_reply *);
2129 	int reply_body_size;
2130 };
2131 
2132 static struct cn_handler_struct cnd_table[] = {
2133 	[ P_primary ]		= { &drbd_nl_primary,		0 },
2134 	[ P_secondary ]		= { &drbd_nl_secondary,		0 },
2135 	[ P_disk_conf ]		= { &drbd_nl_disk_conf,		0 },
2136 	[ P_detach ]		= { &drbd_nl_detach,		0 },
2137 	[ P_net_conf ]		= { &drbd_nl_net_conf,		0 },
2138 	[ P_disconnect ]	= { &drbd_nl_disconnect,	0 },
2139 	[ P_resize ]		= { &drbd_nl_resize,		0 },
2140 	[ P_syncer_conf ]	= { &drbd_nl_syncer_conf,	0 },
2141 	[ P_invalidate ]	= { &drbd_nl_invalidate,	0 },
2142 	[ P_invalidate_peer ]	= { &drbd_nl_invalidate_peer,	0 },
2143 	[ P_pause_sync ]	= { &drbd_nl_pause_sync,	0 },
2144 	[ P_resume_sync ]	= { &drbd_nl_resume_sync,	0 },
2145 	[ P_suspend_io ]	= { &drbd_nl_suspend_io,	0 },
2146 	[ P_resume_io ]		= { &drbd_nl_resume_io,		0 },
2147 	[ P_outdate ]		= { &drbd_nl_outdate,		0 },
2148 	[ P_get_config ]	= { &drbd_nl_get_config,
2149 				    sizeof(struct syncer_conf_tag_len_struct) +
2150 				    sizeof(struct disk_conf_tag_len_struct) +
2151 				    sizeof(struct net_conf_tag_len_struct) },
2152 	[ P_get_state ]		= { &drbd_nl_get_state,
2153 				    sizeof(struct get_state_tag_len_struct) +
2154 				    sizeof(struct sync_progress_tag_len_struct)	},
2155 	[ P_get_uuids ]		= { &drbd_nl_get_uuids,
2156 				    sizeof(struct get_uuids_tag_len_struct) },
2157 	[ P_get_timeout_flag ]	= { &drbd_nl_get_timeout_flag,
2158 				    sizeof(struct get_timeout_flag_tag_len_struct)},
2159 	[ P_start_ov ]		= { &drbd_nl_start_ov,		0 },
2160 	[ P_new_c_uuid ]	= { &drbd_nl_new_c_uuid,	0 },
2161 };
2162 
2163 static void drbd_connector_callback(struct cn_msg *req, struct netlink_skb_parms *nsp)
2164 {
2165 	struct drbd_nl_cfg_req *nlp = (struct drbd_nl_cfg_req *)req->data;
2166 	struct cn_handler_struct *cm;
2167 	struct cn_msg *cn_reply;
2168 	struct drbd_nl_cfg_reply *reply;
2169 	struct drbd_conf *mdev;
2170 	int retcode, rr;
2171 	int reply_size = sizeof(struct cn_msg)
2172 		+ sizeof(struct drbd_nl_cfg_reply)
2173 		+ sizeof(short int);
2174 
2175 	if (!try_module_get(THIS_MODULE)) {
2176 		printk(KERN_ERR "drbd: try_module_get() failed!\n");
2177 		return;
2178 	}
2179 
2180 	if (!cap_raised(nsp->eff_cap, CAP_SYS_ADMIN)) {
2181 		retcode = ERR_PERM;
2182 		goto fail;
2183 	}
2184 
2185 	mdev = ensure_mdev(nlp->drbd_minor,
2186 			(nlp->flags & DRBD_NL_CREATE_DEVICE));
2187 	if (!mdev) {
2188 		retcode = ERR_MINOR_INVALID;
2189 		goto fail;
2190 	}
2191 
2192 	if (nlp->packet_type >= P_nl_after_last_packet) {
2193 		retcode = ERR_PACKET_NR;
2194 		goto fail;
2195 	}
2196 
2197 	cm = cnd_table + nlp->packet_type;
2198 
2199 	/* This may happen if packet number is 0: */
2200 	if (cm->function == NULL) {
2201 		retcode = ERR_PACKET_NR;
2202 		goto fail;
2203 	}
2204 
2205 	reply_size += cm->reply_body_size;
2206 
2207 	/* allocation not in the IO path, cqueue thread context */
2208 	cn_reply = kmalloc(reply_size, GFP_KERNEL);
2209 	if (!cn_reply) {
2210 		retcode = ERR_NOMEM;
2211 		goto fail;
2212 	}
2213 	reply = (struct drbd_nl_cfg_reply *) cn_reply->data;
2214 
2215 	reply->packet_type =
2216 		cm->reply_body_size ? nlp->packet_type : P_nl_after_last_packet;
2217 	reply->minor = nlp->drbd_minor;
2218 	reply->ret_code = NO_ERROR; /* Might by modified by cm->function. */
2219 	/* reply->tag_list; might be modified by cm->function. */
2220 
2221 	rr = cm->function(mdev, nlp, reply);
2222 
2223 	cn_reply->id = req->id;
2224 	cn_reply->seq = req->seq;
2225 	cn_reply->ack = req->ack  + 1;
2226 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply) + rr;
2227 	cn_reply->flags = 0;
2228 
2229 	rr = cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_KERNEL);
2230 	if (rr && rr != -ESRCH)
2231 		printk(KERN_INFO "drbd: cn_netlink_send()=%d\n", rr);
2232 
2233 	kfree(cn_reply);
2234 	module_put(THIS_MODULE);
2235 	return;
2236  fail:
2237 	drbd_nl_send_reply(req, retcode);
2238 	module_put(THIS_MODULE);
2239 }
2240 
2241 static atomic_t drbd_nl_seq = ATOMIC_INIT(2); /* two. */
2242 
2243 static unsigned short *
2244 __tl_add_blob(unsigned short *tl, enum drbd_tags tag, const void *data,
2245 	unsigned short len, int nul_terminated)
2246 {
2247 	unsigned short l = tag_descriptions[tag_number(tag)].max_len;
2248 	len = (len < l) ? len :  l;
2249 	put_unaligned(tag, tl++);
2250 	put_unaligned(len, tl++);
2251 	memcpy(tl, data, len);
2252 	tl = (unsigned short*)((char*)tl + len);
2253 	if (nul_terminated)
2254 		*((char*)tl - 1) = 0;
2255 	return tl;
2256 }
2257 
2258 static unsigned short *
2259 tl_add_blob(unsigned short *tl, enum drbd_tags tag, const void *data, int len)
2260 {
2261 	return __tl_add_blob(tl, tag, data, len, 0);
2262 }
2263 
2264 static unsigned short *
2265 tl_add_str(unsigned short *tl, enum drbd_tags tag, const char *str)
2266 {
2267 	return __tl_add_blob(tl, tag, str, strlen(str)+1, 0);
2268 }
2269 
2270 static unsigned short *
2271 tl_add_int(unsigned short *tl, enum drbd_tags tag, const void *val)
2272 {
2273 	put_unaligned(tag, tl++);
2274 	switch(tag_type(tag)) {
2275 	case TT_INTEGER:
2276 		put_unaligned(sizeof(int), tl++);
2277 		put_unaligned(*(int *)val, (int *)tl);
2278 		tl = (unsigned short*)((char*)tl+sizeof(int));
2279 		break;
2280 	case TT_INT64:
2281 		put_unaligned(sizeof(u64), tl++);
2282 		put_unaligned(*(u64 *)val, (u64 *)tl);
2283 		tl = (unsigned short*)((char*)tl+sizeof(u64));
2284 		break;
2285 	default:
2286 		/* someone did something stupid. */
2287 		;
2288 	}
2289 	return tl;
2290 }
2291 
2292 void drbd_bcast_state(struct drbd_conf *mdev, union drbd_state state)
2293 {
2294 	char buffer[sizeof(struct cn_msg)+
2295 		    sizeof(struct drbd_nl_cfg_reply)+
2296 		    sizeof(struct get_state_tag_len_struct)+
2297 		    sizeof(short int)];
2298 	struct cn_msg *cn_reply = (struct cn_msg *) buffer;
2299 	struct drbd_nl_cfg_reply *reply =
2300 		(struct drbd_nl_cfg_reply *)cn_reply->data;
2301 	unsigned short *tl = reply->tag_list;
2302 
2303 	/* dev_warn(DEV, "drbd_bcast_state() got called\n"); */
2304 
2305 	tl = get_state_to_tags(mdev, (struct get_state *)&state, tl);
2306 
2307 	put_unaligned(TT_END, tl++); /* Close the tag list */
2308 
2309 	cn_reply->id.idx = CN_IDX_DRBD;
2310 	cn_reply->id.val = CN_VAL_DRBD;
2311 
2312 	cn_reply->seq = atomic_add_return(1, &drbd_nl_seq);
2313 	cn_reply->ack = 0; /* not used here. */
2314 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply) +
2315 		(int)((char *)tl - (char *)reply->tag_list);
2316 	cn_reply->flags = 0;
2317 
2318 	reply->packet_type = P_get_state;
2319 	reply->minor = mdev_to_minor(mdev);
2320 	reply->ret_code = NO_ERROR;
2321 
2322 	cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_NOIO);
2323 }
2324 
2325 void drbd_bcast_ev_helper(struct drbd_conf *mdev, char *helper_name)
2326 {
2327 	char buffer[sizeof(struct cn_msg)+
2328 		    sizeof(struct drbd_nl_cfg_reply)+
2329 		    sizeof(struct call_helper_tag_len_struct)+
2330 		    sizeof(short int)];
2331 	struct cn_msg *cn_reply = (struct cn_msg *) buffer;
2332 	struct drbd_nl_cfg_reply *reply =
2333 		(struct drbd_nl_cfg_reply *)cn_reply->data;
2334 	unsigned short *tl = reply->tag_list;
2335 
2336 	/* dev_warn(DEV, "drbd_bcast_state() got called\n"); */
2337 
2338 	tl = tl_add_str(tl, T_helper, helper_name);
2339 	put_unaligned(TT_END, tl++); /* Close the tag list */
2340 
2341 	cn_reply->id.idx = CN_IDX_DRBD;
2342 	cn_reply->id.val = CN_VAL_DRBD;
2343 
2344 	cn_reply->seq = atomic_add_return(1, &drbd_nl_seq);
2345 	cn_reply->ack = 0; /* not used here. */
2346 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply) +
2347 		(int)((char *)tl - (char *)reply->tag_list);
2348 	cn_reply->flags = 0;
2349 
2350 	reply->packet_type = P_call_helper;
2351 	reply->minor = mdev_to_minor(mdev);
2352 	reply->ret_code = NO_ERROR;
2353 
2354 	cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_NOIO);
2355 }
2356 
2357 void drbd_bcast_ee(struct drbd_conf *mdev,
2358 		const char *reason, const int dgs,
2359 		const char* seen_hash, const char* calc_hash,
2360 		const struct drbd_epoch_entry* e)
2361 {
2362 	struct cn_msg *cn_reply;
2363 	struct drbd_nl_cfg_reply *reply;
2364 	unsigned short *tl;
2365 	struct page *page;
2366 	unsigned len;
2367 
2368 	if (!e)
2369 		return;
2370 	if (!reason || !reason[0])
2371 		return;
2372 
2373 	/* apparently we have to memcpy twice, first to prepare the data for the
2374 	 * struct cn_msg, then within cn_netlink_send from the cn_msg to the
2375 	 * netlink skb. */
2376 	/* receiver thread context, which is not in the writeout path (of this node),
2377 	 * but may be in the writeout path of the _other_ node.
2378 	 * GFP_NOIO to avoid potential "distributed deadlock". */
2379 	cn_reply = kmalloc(
2380 		sizeof(struct cn_msg)+
2381 		sizeof(struct drbd_nl_cfg_reply)+
2382 		sizeof(struct dump_ee_tag_len_struct)+
2383 		sizeof(short int),
2384 		GFP_NOIO);
2385 
2386 	if (!cn_reply) {
2387 		dev_err(DEV, "could not kmalloc buffer for drbd_bcast_ee, sector %llu, size %u\n",
2388 				(unsigned long long)e->sector, e->size);
2389 		return;
2390 	}
2391 
2392 	reply = (struct drbd_nl_cfg_reply*)cn_reply->data;
2393 	tl = reply->tag_list;
2394 
2395 	tl = tl_add_str(tl, T_dump_ee_reason, reason);
2396 	tl = tl_add_blob(tl, T_seen_digest, seen_hash, dgs);
2397 	tl = tl_add_blob(tl, T_calc_digest, calc_hash, dgs);
2398 	tl = tl_add_int(tl, T_ee_sector, &e->sector);
2399 	tl = tl_add_int(tl, T_ee_block_id, &e->block_id);
2400 
2401 	put_unaligned(T_ee_data, tl++);
2402 	put_unaligned(e->size, tl++);
2403 
2404 	len = e->size;
2405 	page = e->pages;
2406 	page_chain_for_each(page) {
2407 		void *d = kmap_atomic(page, KM_USER0);
2408 		unsigned l = min_t(unsigned, len, PAGE_SIZE);
2409 		memcpy(tl, d, l);
2410 		kunmap_atomic(d, KM_USER0);
2411 		tl = (unsigned short*)((char*)tl + l);
2412 		len -= l;
2413 	}
2414 	put_unaligned(TT_END, tl++); /* Close the tag list */
2415 
2416 	cn_reply->id.idx = CN_IDX_DRBD;
2417 	cn_reply->id.val = CN_VAL_DRBD;
2418 
2419 	cn_reply->seq = atomic_add_return(1,&drbd_nl_seq);
2420 	cn_reply->ack = 0; // not used here.
2421 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply) +
2422 		(int)((char*)tl - (char*)reply->tag_list);
2423 	cn_reply->flags = 0;
2424 
2425 	reply->packet_type = P_dump_ee;
2426 	reply->minor = mdev_to_minor(mdev);
2427 	reply->ret_code = NO_ERROR;
2428 
2429 	cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_NOIO);
2430 	kfree(cn_reply);
2431 }
2432 
2433 void drbd_bcast_sync_progress(struct drbd_conf *mdev)
2434 {
2435 	char buffer[sizeof(struct cn_msg)+
2436 		    sizeof(struct drbd_nl_cfg_reply)+
2437 		    sizeof(struct sync_progress_tag_len_struct)+
2438 		    sizeof(short int)];
2439 	struct cn_msg *cn_reply = (struct cn_msg *) buffer;
2440 	struct drbd_nl_cfg_reply *reply =
2441 		(struct drbd_nl_cfg_reply *)cn_reply->data;
2442 	unsigned short *tl = reply->tag_list;
2443 	unsigned long rs_left;
2444 	unsigned int res;
2445 
2446 	/* no local ref, no bitmap, no syncer progress, no broadcast. */
2447 	if (!get_ldev(mdev))
2448 		return;
2449 	drbd_get_syncer_progress(mdev, &rs_left, &res);
2450 	put_ldev(mdev);
2451 
2452 	tl = tl_add_int(tl, T_sync_progress, &res);
2453 	put_unaligned(TT_END, tl++); /* Close the tag list */
2454 
2455 	cn_reply->id.idx = CN_IDX_DRBD;
2456 	cn_reply->id.val = CN_VAL_DRBD;
2457 
2458 	cn_reply->seq = atomic_add_return(1, &drbd_nl_seq);
2459 	cn_reply->ack = 0; /* not used here. */
2460 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply) +
2461 		(int)((char *)tl - (char *)reply->tag_list);
2462 	cn_reply->flags = 0;
2463 
2464 	reply->packet_type = P_sync_progress;
2465 	reply->minor = mdev_to_minor(mdev);
2466 	reply->ret_code = NO_ERROR;
2467 
2468 	cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_NOIO);
2469 }
2470 
2471 int __init drbd_nl_init(void)
2472 {
2473 	static struct cb_id cn_id_drbd;
2474 	int err, try=10;
2475 
2476 	cn_id_drbd.val = CN_VAL_DRBD;
2477 	do {
2478 		cn_id_drbd.idx = cn_idx;
2479 		err = cn_add_callback(&cn_id_drbd, "cn_drbd", &drbd_connector_callback);
2480 		if (!err)
2481 			break;
2482 		cn_idx = (cn_idx + CN_IDX_STEP);
2483 	} while (try--);
2484 
2485 	if (err) {
2486 		printk(KERN_ERR "drbd: cn_drbd failed to register\n");
2487 		return err;
2488 	}
2489 
2490 	return 0;
2491 }
2492 
2493 void drbd_nl_cleanup(void)
2494 {
2495 	static struct cb_id cn_id_drbd;
2496 
2497 	cn_id_drbd.idx = cn_idx;
2498 	cn_id_drbd.val = CN_VAL_DRBD;
2499 
2500 	cn_del_callback(&cn_id_drbd);
2501 }
2502 
2503 void drbd_nl_send_reply(struct cn_msg *req, int ret_code)
2504 {
2505 	char buffer[sizeof(struct cn_msg)+sizeof(struct drbd_nl_cfg_reply)];
2506 	struct cn_msg *cn_reply = (struct cn_msg *) buffer;
2507 	struct drbd_nl_cfg_reply *reply =
2508 		(struct drbd_nl_cfg_reply *)cn_reply->data;
2509 	int rr;
2510 
2511 	cn_reply->id = req->id;
2512 
2513 	cn_reply->seq = req->seq;
2514 	cn_reply->ack = req->ack  + 1;
2515 	cn_reply->len = sizeof(struct drbd_nl_cfg_reply);
2516 	cn_reply->flags = 0;
2517 
2518 	reply->minor = ((struct drbd_nl_cfg_req *)req->data)->drbd_minor;
2519 	reply->ret_code = ret_code;
2520 
2521 	rr = cn_netlink_send(cn_reply, CN_IDX_DRBD, GFP_NOIO);
2522 	if (rr && rr != -ESRCH)
2523 		printk(KERN_INFO "drbd: cn_netlink_send()=%d\n", rr);
2524 }
2525 
2526