xref: /linux/drivers/block/drbd/drbd_nl.c (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3    drbd_nl.c
4 
5    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
6 
7    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
8    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
9    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
10 
11 
12  */
13 
14 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
15 
16 #include <linux/module.h>
17 #include <linux/umh.h>
18 #include <linux/drbd.h>
19 #include <linux/in.h>
20 #include <linux/fs.h>
21 #include <linux/file.h>
22 #include <linux/slab.h>
23 #include <linux/blkpg.h>
24 #include <linux/cpumask.h>
25 #include "drbd_int.h"
26 #include "drbd_protocol.h"
27 #include "drbd_req.h"
28 #include "drbd_state_change.h"
29 #include <linux/unaligned.h>
30 #include <linux/drbd_limits.h>
31 #include <linux/kthread.h>
32 
33 #include <net/genetlink.h>
34 
35 #include "drbd_nl_gen.h"
36 
37 static int drbd_genl_multicast_events(struct sk_buff *skb, gfp_t flags)
38 {
39 	return genlmsg_multicast(&drbd_nl_family, skb, 0,
40 				 DRBD_NLGRP_EVENTS, flags);
41 }
42 
43 static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
44 static atomic_t notify_genl_seq = ATOMIC_INIT(2); /* two. */
45 
46 DEFINE_MUTEX(notification_mutex);
47 
48 /* used bdev_open_by_path, to claim our meta data device(s) */
49 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
50 
51 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
52 {
53 	genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
54 	if (genlmsg_reply(skb, info))
55 		pr_err("error sending genl reply\n");
56 }
57 
58 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
59  * reason it could fail was no space in skb, and there are 4k available. */
60 static int drbd_msg_put_info(struct sk_buff *skb, const char *info)
61 {
62 	struct nlattr *nla;
63 	int err = -EMSGSIZE;
64 
65 	if (!info || !info[0])
66 		return 0;
67 
68 	nla = nla_nest_start_noflag(skb, DRBD_NLA_CFG_REPLY);
69 	if (!nla)
70 		return err;
71 
72 	err = nla_put_string(skb, DRBD_A_DRBD_CFG_REPLY_INFO_TEXT, info);
73 	if (err) {
74 		nla_nest_cancel(skb, nla);
75 		return err;
76 	} else
77 		nla_nest_end(skb, nla);
78 	return 0;
79 }
80 
81 __printf(2, 3)
82 static int drbd_msg_sprintf_info(struct sk_buff *skb, const char *fmt, ...)
83 {
84 	va_list args;
85 	struct nlattr *nla, *txt;
86 	int err = -EMSGSIZE;
87 	int len;
88 
89 	nla = nla_nest_start_noflag(skb, DRBD_NLA_CFG_REPLY);
90 	if (!nla)
91 		return err;
92 
93 	txt = nla_reserve(skb, DRBD_A_DRBD_CFG_REPLY_INFO_TEXT, 256);
94 	if (!txt) {
95 		nla_nest_cancel(skb, nla);
96 		return err;
97 	}
98 	va_start(args, fmt);
99 	len = vscnprintf(nla_data(txt), 256, fmt, args);
100 	va_end(args);
101 
102 	/* maybe: retry with larger reserve, if truncated */
103 	txt->nla_len = nla_attr_size(len+1);
104 	nlmsg_trim(skb, (char*)txt + NLA_ALIGN(txt->nla_len));
105 	nla_nest_end(skb, nla);
106 
107 	return 0;
108 }
109 
110 /* Flags for drbd_adm_prepare() */
111 #define DRBD_ADM_NEED_MINOR	 (1 << 0)
112 #define DRBD_ADM_NEED_RESOURCE	 (1 << 1)
113 #define DRBD_ADM_NEED_CONNECTION (1 << 2)
114 
115 /* Per-command flags for drbd_pre_doit() */
116 static const unsigned int drbd_genl_cmd_flags[] = {
117 	[DRBD_ADM_GET_STATUS]     = DRBD_ADM_NEED_MINOR,
118 	[DRBD_ADM_NEW_MINOR]      = DRBD_ADM_NEED_RESOURCE,
119 	[DRBD_ADM_DEL_MINOR]      = DRBD_ADM_NEED_MINOR,
120 	[DRBD_ADM_NEW_RESOURCE]   = 0,
121 	[DRBD_ADM_DEL_RESOURCE]   = DRBD_ADM_NEED_RESOURCE,
122 	[DRBD_ADM_RESOURCE_OPTS]  = DRBD_ADM_NEED_RESOURCE,
123 	[DRBD_ADM_CONNECT]        = DRBD_ADM_NEED_RESOURCE,
124 	[DRBD_ADM_CHG_NET_OPTS]   = DRBD_ADM_NEED_CONNECTION,
125 	[DRBD_ADM_DISCONNECT]     = DRBD_ADM_NEED_CONNECTION,
126 	[DRBD_ADM_ATTACH]         = DRBD_ADM_NEED_MINOR,
127 	[DRBD_ADM_CHG_DISK_OPTS]  = DRBD_ADM_NEED_MINOR,
128 	[DRBD_ADM_RESIZE]         = DRBD_ADM_NEED_MINOR,
129 	[DRBD_ADM_PRIMARY]        = DRBD_ADM_NEED_MINOR,
130 	[DRBD_ADM_SECONDARY]      = DRBD_ADM_NEED_MINOR,
131 	[DRBD_ADM_NEW_C_UUID]     = DRBD_ADM_NEED_MINOR,
132 	[DRBD_ADM_START_OV]       = DRBD_ADM_NEED_MINOR,
133 	[DRBD_ADM_DETACH]         = DRBD_ADM_NEED_MINOR,
134 	[DRBD_ADM_INVALIDATE]     = DRBD_ADM_NEED_MINOR,
135 	[DRBD_ADM_INVAL_PEER]     = DRBD_ADM_NEED_MINOR,
136 	[DRBD_ADM_PAUSE_SYNC]     = DRBD_ADM_NEED_MINOR,
137 	[DRBD_ADM_RESUME_SYNC]    = DRBD_ADM_NEED_MINOR,
138 	[DRBD_ADM_SUSPEND_IO]     = DRBD_ADM_NEED_MINOR,
139 	[DRBD_ADM_RESUME_IO]      = DRBD_ADM_NEED_MINOR,
140 	[DRBD_ADM_OUTDATE]        = DRBD_ADM_NEED_MINOR,
141 	[DRBD_ADM_GET_TIMEOUT_TYPE] = DRBD_ADM_NEED_MINOR,
142 	[DRBD_ADM_DOWN]           = DRBD_ADM_NEED_RESOURCE,
143 };
144 
145 /* Detect attempts to change invariant attributes in a _change_ handler. */
146 #define has_invariant(ntb, attr)						\
147 ({									\
148 	bool __found = !!(ntb)[attr];					\
149 	if (__found)							\
150 		pr_info("must not change invariant attr: %s\n", #attr);	\
151 	__found;							\
152 })
153 
154 /*
155  * At this point, we still rely on the global genl_lock().
156  * If we want to avoid that, and allow "genl_family.parallel_ops", we may need
157  * to add additional synchronization against object destruction/modification.
158  */
159 static int drbd_adm_prepare(struct drbd_config_context *adm_ctx,
160 	struct sk_buff *skb, struct genl_info *info, unsigned flags)
161 {
162 	struct drbd_genlmsghdr *d_in = genl_info_userhdr(info);
163 	const u8 cmd = info->genlhdr->cmd;
164 	int err;
165 
166 	/* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
167 	if (cmd != DRBD_ADM_GET_STATUS && !capable(CAP_NET_ADMIN))
168 	       return -EPERM;
169 
170 	adm_ctx->reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
171 	if (!adm_ctx->reply_skb) {
172 		err = -ENOMEM;
173 		goto fail;
174 	}
175 
176 	adm_ctx->reply_dh = genlmsg_put_reply(adm_ctx->reply_skb,
177 					info, &drbd_nl_family, 0, cmd);
178 	/* put of a few bytes into a fresh skb of >= 4k will always succeed.
179 	 * but anyways */
180 	if (!adm_ctx->reply_dh) {
181 		err = -ENOMEM;
182 		goto fail;
183 	}
184 
185 	adm_ctx->reply_dh->minor = d_in->minor;
186 	adm_ctx->reply_dh->ret_code = NO_ERROR;
187 
188 	adm_ctx->volume = VOLUME_UNSPECIFIED;
189 	if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
190 		struct nlattr **ntb;
191 		struct nlattr *nla;
192 
193 		/* parse and validate, get nested attribute table */
194 		err = drbd_cfg_context_ntb_from_attrs(&ntb, info);
195 		if (err)
196 			goto fail;
197 
198 		/* It was present, and valid,
199 		 * copy it over to the reply skb. */
200 		err = nla_put_nohdr(adm_ctx->reply_skb,
201 				info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
202 				info->attrs[DRBD_NLA_CFG_CONTEXT]);
203 		if (err) {
204 			kfree(ntb);
205 			goto fail;
206 		}
207 
208 		/* and assign stuff to the adm_ctx */
209 		nla = ntb[DRBD_A_DRBD_CFG_CONTEXT_CTX_VOLUME];
210 		if (nla)
211 			adm_ctx->volume = nla_get_u32(nla);
212 		nla = ntb[DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME];
213 		if (nla)
214 			adm_ctx->resource_name = nla_data(nla);
215 		adm_ctx->my_addr = ntb[DRBD_A_DRBD_CFG_CONTEXT_CTX_MY_ADDR];
216 		adm_ctx->peer_addr = ntb[DRBD_A_DRBD_CFG_CONTEXT_CTX_PEER_ADDR];
217 		kfree(ntb);
218 		if ((adm_ctx->my_addr &&
219 		     nla_len(adm_ctx->my_addr) > sizeof(adm_ctx->connection->my_addr)) ||
220 		    (adm_ctx->peer_addr &&
221 		     nla_len(adm_ctx->peer_addr) > sizeof(adm_ctx->connection->peer_addr))) {
222 			err = -EINVAL;
223 			goto fail;
224 		}
225 	}
226 
227 	adm_ctx->minor = d_in->minor;
228 	adm_ctx->device = minor_to_device(d_in->minor);
229 
230 	/* We are protected by the global genl_lock().
231 	 * But we may explicitly drop it/retake it in drbd_nl_set_role(),
232 	 * so make sure this object stays around. */
233 	if (adm_ctx->device)
234 		kref_get(&adm_ctx->device->kref);
235 
236 	if (adm_ctx->resource_name) {
237 		adm_ctx->resource = drbd_find_resource(adm_ctx->resource_name);
238 	}
239 
240 	if (!adm_ctx->device && (flags & DRBD_ADM_NEED_MINOR)) {
241 		drbd_msg_put_info(adm_ctx->reply_skb, "unknown minor");
242 		return ERR_MINOR_INVALID;
243 	}
244 	if (!adm_ctx->resource && (flags & DRBD_ADM_NEED_RESOURCE)) {
245 		drbd_msg_put_info(adm_ctx->reply_skb, "unknown resource");
246 		if (adm_ctx->resource_name)
247 			return ERR_RES_NOT_KNOWN;
248 		return ERR_INVALID_REQUEST;
249 	}
250 
251 	if (flags & DRBD_ADM_NEED_CONNECTION) {
252 		if (adm_ctx->resource) {
253 			drbd_msg_put_info(adm_ctx->reply_skb, "no resource name expected");
254 			return ERR_INVALID_REQUEST;
255 		}
256 		if (adm_ctx->device) {
257 			drbd_msg_put_info(adm_ctx->reply_skb, "no minor number expected");
258 			return ERR_INVALID_REQUEST;
259 		}
260 		if (adm_ctx->my_addr && adm_ctx->peer_addr)
261 			adm_ctx->connection = conn_get_by_addrs(nla_data(adm_ctx->my_addr),
262 							  nla_len(adm_ctx->my_addr),
263 							  nla_data(adm_ctx->peer_addr),
264 							  nla_len(adm_ctx->peer_addr));
265 		if (!adm_ctx->connection) {
266 			drbd_msg_put_info(adm_ctx->reply_skb, "unknown connection");
267 			return ERR_INVALID_REQUEST;
268 		}
269 	}
270 
271 	/* some more paranoia, if the request was over-determined */
272 	if (adm_ctx->device && adm_ctx->resource &&
273 	    adm_ctx->device->resource != adm_ctx->resource) {
274 		pr_warn("request: minor=%u, resource=%s; but that minor belongs to resource %s\n",
275 			adm_ctx->minor, adm_ctx->resource->name,
276 			adm_ctx->device->resource->name);
277 		drbd_msg_put_info(adm_ctx->reply_skb, "minor exists in different resource");
278 		return ERR_INVALID_REQUEST;
279 	}
280 	if (adm_ctx->device &&
281 	    adm_ctx->volume != VOLUME_UNSPECIFIED &&
282 	    adm_ctx->volume != adm_ctx->device->vnr) {
283 		pr_warn("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
284 			adm_ctx->minor, adm_ctx->volume,
285 			adm_ctx->device->vnr, adm_ctx->device->resource->name);
286 		drbd_msg_put_info(adm_ctx->reply_skb, "minor exists as different volume");
287 		return ERR_INVALID_REQUEST;
288 	}
289 
290 	/* still, provide adm_ctx->resource always, if possible. */
291 	if (!adm_ctx->resource) {
292 		adm_ctx->resource = adm_ctx->device ? adm_ctx->device->resource
293 			: adm_ctx->connection ? adm_ctx->connection->resource : NULL;
294 		if (adm_ctx->resource)
295 			kref_get(&adm_ctx->resource->kref);
296 	}
297 
298 	return NO_ERROR;
299 
300 fail:
301 	nlmsg_free(adm_ctx->reply_skb);
302 	adm_ctx->reply_skb = NULL;
303 	return err;
304 }
305 
306 int drbd_pre_doit(const struct genl_split_ops *ops,
307 		  struct sk_buff *skb, struct genl_info *info)
308 {
309 	struct drbd_config_context *adm_ctx;
310 	u8 cmd = info->genlhdr->cmd;
311 	unsigned int flags;
312 	int err;
313 
314 	adm_ctx = kzalloc_obj(*adm_ctx);
315 	if (!adm_ctx)
316 		return -ENOMEM;
317 
318 	flags = (cmd < ARRAY_SIZE(drbd_genl_cmd_flags))
319 		? drbd_genl_cmd_flags[cmd] : 0;
320 
321 	err = drbd_adm_prepare(adm_ctx, skb, info, flags);
322 	if (err && !adm_ctx->reply_skb) {
323 		/* Fatal error before reply_skb was allocated. */
324 		kfree(adm_ctx);
325 		return err;
326 	}
327 	if (err)
328 		adm_ctx->reply_dh->ret_code = err;
329 
330 	info->user_ptr[0] = adm_ctx;
331 	return 0;
332 }
333 
334 void drbd_post_doit(const struct genl_split_ops *ops,
335 		    struct sk_buff *skb, struct genl_info *info)
336 {
337 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
338 
339 	if (!adm_ctx)
340 		return;
341 
342 	if (adm_ctx->reply_skb)
343 		drbd_adm_send_reply(adm_ctx->reply_skb, info);
344 
345 	if (adm_ctx->device) {
346 		kref_put(&adm_ctx->device->kref, drbd_destroy_device);
347 		adm_ctx->device = NULL;
348 	}
349 	if (adm_ctx->connection) {
350 		kref_put(&adm_ctx->connection->kref, &drbd_destroy_connection);
351 		adm_ctx->connection = NULL;
352 	}
353 	if (adm_ctx->resource) {
354 		kref_put(&adm_ctx->resource->kref, drbd_destroy_resource);
355 		adm_ctx->resource = NULL;
356 	}
357 
358 	kfree(adm_ctx);
359 }
360 
361 static void setup_khelper_env(struct drbd_connection *connection, char **envp)
362 {
363 	char *afs;
364 
365 	/* FIXME: A future version will not allow this case. */
366 	if (connection->my_addr_len == 0 || connection->peer_addr_len == 0)
367 		return;
368 
369 	switch (((struct sockaddr *)&connection->peer_addr)->sa_family) {
370 	case AF_INET6:
371 		afs = "ipv6";
372 		snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
373 			 &((struct sockaddr_in6 *)&connection->peer_addr)->sin6_addr);
374 		break;
375 	case AF_INET:
376 		afs = "ipv4";
377 		snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
378 			 &((struct sockaddr_in *)&connection->peer_addr)->sin_addr);
379 		break;
380 	default:
381 		afs = "ssocks";
382 		snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
383 			 &((struct sockaddr_in *)&connection->peer_addr)->sin_addr);
384 	}
385 	snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
386 }
387 
388 int drbd_khelper(struct drbd_device *device, char *cmd)
389 {
390 	char *envp[] = { "HOME=/",
391 			"TERM=linux",
392 			"PATH=/sbin:/usr/sbin:/bin:/usr/bin",
393 			 (char[20]) { }, /* address family */
394 			 (char[60]) { }, /* address */
395 			NULL };
396 	char mb[14];
397 	char *argv[] = {drbd_usermode_helper, cmd, mb, NULL };
398 	struct drbd_connection *connection = first_peer_device(device)->connection;
399 	struct sib_info sib;
400 	int ret;
401 
402 	if (current == connection->worker.task)
403 		set_bit(CALLBACK_PENDING, &connection->flags);
404 
405 	snprintf(mb, 14, "minor-%d", device_to_minor(device));
406 	setup_khelper_env(connection, envp);
407 
408 	/* The helper may take some time.
409 	 * write out any unsynced meta data changes now */
410 	drbd_md_sync(device);
411 
412 	drbd_info(device, "helper command: %s %s %s\n", drbd_usermode_helper, cmd, mb);
413 	sib.sib_reason = SIB_HELPER_PRE;
414 	sib.helper_name = cmd;
415 	drbd_bcast_event(device, &sib);
416 	notify_helper(NOTIFY_CALL, device, connection, cmd, 0);
417 	ret = call_usermodehelper(drbd_usermode_helper, argv, envp, UMH_WAIT_PROC);
418 	if (ret)
419 		drbd_warn(device, "helper command: %s %s %s exit code %u (0x%x)\n",
420 				drbd_usermode_helper, cmd, mb,
421 				(ret >> 8) & 0xff, ret);
422 	else
423 		drbd_info(device, "helper command: %s %s %s exit code %u (0x%x)\n",
424 				drbd_usermode_helper, cmd, mb,
425 				(ret >> 8) & 0xff, ret);
426 	sib.sib_reason = SIB_HELPER_POST;
427 	sib.helper_exit_code = ret;
428 	drbd_bcast_event(device, &sib);
429 	notify_helper(NOTIFY_RESPONSE, device, connection, cmd, ret);
430 
431 	if (current == connection->worker.task)
432 		clear_bit(CALLBACK_PENDING, &connection->flags);
433 
434 	if (ret < 0) /* Ignore any ERRNOs we got. */
435 		ret = 0;
436 
437 	return ret;
438 }
439 
440 enum drbd_peer_state conn_khelper(struct drbd_connection *connection, char *cmd)
441 {
442 	char *envp[] = { "HOME=/",
443 			"TERM=linux",
444 			"PATH=/sbin:/usr/sbin:/bin:/usr/bin",
445 			 (char[20]) { }, /* address family */
446 			 (char[60]) { }, /* address */
447 			NULL };
448 	char *resource_name = connection->resource->name;
449 	char *argv[] = {drbd_usermode_helper, cmd, resource_name, NULL };
450 	int ret;
451 
452 	setup_khelper_env(connection, envp);
453 	conn_md_sync(connection);
454 
455 	drbd_info(connection, "helper command: %s %s %s\n", drbd_usermode_helper, cmd, resource_name);
456 	/* TODO: conn_bcast_event() ?? */
457 	notify_helper(NOTIFY_CALL, NULL, connection, cmd, 0);
458 
459 	ret = call_usermodehelper(drbd_usermode_helper, argv, envp, UMH_WAIT_PROC);
460 	if (ret)
461 		drbd_warn(connection, "helper command: %s %s %s exit code %u (0x%x)\n",
462 			  drbd_usermode_helper, cmd, resource_name,
463 			  (ret >> 8) & 0xff, ret);
464 	else
465 		drbd_info(connection, "helper command: %s %s %s exit code %u (0x%x)\n",
466 			  drbd_usermode_helper, cmd, resource_name,
467 			  (ret >> 8) & 0xff, ret);
468 	/* TODO: conn_bcast_event() ?? */
469 	notify_helper(NOTIFY_RESPONSE, NULL, connection, cmd, ret);
470 
471 	if (ret < 0) /* Ignore any ERRNOs we got. */
472 		ret = 0;
473 
474 	return ret;
475 }
476 
477 static enum drbd_fencing_p highest_fencing_policy(struct drbd_connection *connection)
478 {
479 	enum drbd_fencing_p fp = FP_NOT_AVAIL;
480 	struct drbd_peer_device *peer_device;
481 	int vnr;
482 
483 	rcu_read_lock();
484 	idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
485 		struct drbd_device *device = peer_device->device;
486 		if (get_ldev_if_state(device, D_CONSISTENT)) {
487 			struct disk_conf *disk_conf =
488 				rcu_dereference(peer_device->device->ldev->disk_conf);
489 			fp = max_t(enum drbd_fencing_p, fp, disk_conf->fencing);
490 			put_ldev(device);
491 		}
492 	}
493 	rcu_read_unlock();
494 
495 	return fp;
496 }
497 
498 static bool resource_is_supended(struct drbd_resource *resource)
499 {
500 	return resource->susp || resource->susp_fen || resource->susp_nod;
501 }
502 
503 bool conn_try_outdate_peer(struct drbd_connection *connection)
504 {
505 	struct drbd_resource * const resource = connection->resource;
506 	unsigned int connect_cnt;
507 	union drbd_state mask = { };
508 	union drbd_state val = { };
509 	enum drbd_fencing_p fp;
510 	char *ex_to_string;
511 	int r;
512 
513 	spin_lock_irq(&resource->req_lock);
514 	if (connection->cstate >= C_WF_REPORT_PARAMS) {
515 		drbd_err(connection, "Expected cstate < C_WF_REPORT_PARAMS\n");
516 		spin_unlock_irq(&resource->req_lock);
517 		return false;
518 	}
519 
520 	connect_cnt = connection->connect_cnt;
521 	spin_unlock_irq(&resource->req_lock);
522 
523 	fp = highest_fencing_policy(connection);
524 	switch (fp) {
525 	case FP_NOT_AVAIL:
526 		drbd_warn(connection, "Not fencing peer, I'm not even Consistent myself.\n");
527 		spin_lock_irq(&resource->req_lock);
528 		if (connection->cstate < C_WF_REPORT_PARAMS) {
529 			_conn_request_state(connection,
530 					    (union drbd_state) { { .susp_fen = 1 } },
531 					    (union drbd_state) { { .susp_fen = 0 } },
532 					    CS_VERBOSE | CS_HARD | CS_DC_SUSP);
533 			/* We are no longer suspended due to the fencing policy.
534 			 * We may still be suspended due to the on-no-data-accessible policy.
535 			 * If that was OND_IO_ERROR, fail pending requests. */
536 			if (!resource_is_supended(resource))
537 				_tl_restart(connection, CONNECTION_LOST_WHILE_PENDING);
538 		}
539 		/* Else: in case we raced with a connection handshake,
540 		 * let the handshake figure out if we maybe can RESEND,
541 		 * and do not resume/fail pending requests here.
542 		 * Worst case is we stay suspended for now, which may be
543 		 * resolved by either re-establishing the replication link, or
544 		 * the next link failure, or eventually the administrator.  */
545 		spin_unlock_irq(&resource->req_lock);
546 		return false;
547 
548 	case FP_DONT_CARE:
549 		return true;
550 	default: ;
551 	}
552 
553 	r = conn_khelper(connection, "fence-peer");
554 
555 	switch ((r>>8) & 0xff) {
556 	case P_INCONSISTENT: /* peer is inconsistent */
557 		ex_to_string = "peer is inconsistent or worse";
558 		mask.pdsk = D_MASK;
559 		val.pdsk = D_INCONSISTENT;
560 		break;
561 	case P_OUTDATED: /* peer got outdated, or was already outdated */
562 		ex_to_string = "peer was fenced";
563 		mask.pdsk = D_MASK;
564 		val.pdsk = D_OUTDATED;
565 		break;
566 	case P_DOWN: /* peer was down */
567 		if (conn_highest_disk(connection) == D_UP_TO_DATE) {
568 			/* we will(have) create(d) a new UUID anyways... */
569 			ex_to_string = "peer is unreachable, assumed to be dead";
570 			mask.pdsk = D_MASK;
571 			val.pdsk = D_OUTDATED;
572 		} else {
573 			ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
574 		}
575 		break;
576 	case P_PRIMARY: /* Peer is primary, voluntarily outdate myself.
577 		 * This is useful when an unconnected R_SECONDARY is asked to
578 		 * become R_PRIMARY, but finds the other peer being active. */
579 		ex_to_string = "peer is active";
580 		drbd_warn(connection, "Peer is primary, outdating myself.\n");
581 		mask.disk = D_MASK;
582 		val.disk = D_OUTDATED;
583 		break;
584 	case P_FENCING:
585 		/* THINK: do we need to handle this
586 		 * like case 4, or more like case 5? */
587 		if (fp != FP_STONITH)
588 			drbd_err(connection, "fence-peer() = 7 && fencing != Stonith !!!\n");
589 		ex_to_string = "peer was stonithed";
590 		mask.pdsk = D_MASK;
591 		val.pdsk = D_OUTDATED;
592 		break;
593 	default:
594 		/* The script is broken ... */
595 		drbd_err(connection, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
596 		return false; /* Eventually leave IO frozen */
597 	}
598 
599 	drbd_info(connection, "fence-peer helper returned %d (%s)\n",
600 		  (r>>8) & 0xff, ex_to_string);
601 
602 	/* Not using
603 	   conn_request_state(connection, mask, val, CS_VERBOSE);
604 	   here, because we might were able to re-establish the connection in the
605 	   meantime. */
606 	spin_lock_irq(&resource->req_lock);
607 	if (connection->cstate < C_WF_REPORT_PARAMS && !test_bit(STATE_SENT, &connection->flags)) {
608 		if (connection->connect_cnt != connect_cnt)
609 			/* In case the connection was established and droped
610 			   while the fence-peer handler was running, ignore it */
611 			drbd_info(connection, "Ignoring fence-peer exit code\n");
612 		else
613 			_conn_request_state(connection, mask, val, CS_VERBOSE);
614 	}
615 	spin_unlock_irq(&resource->req_lock);
616 
617 	return conn_highest_pdsk(connection) <= D_OUTDATED;
618 }
619 
620 static int _try_outdate_peer_async(void *data)
621 {
622 	struct drbd_connection *connection = (struct drbd_connection *)data;
623 
624 	conn_try_outdate_peer(connection);
625 
626 	kref_put(&connection->kref, drbd_destroy_connection);
627 	return 0;
628 }
629 
630 void conn_try_outdate_peer_async(struct drbd_connection *connection)
631 {
632 	struct task_struct *opa;
633 
634 	kref_get(&connection->kref);
635 	/* We may have just sent a signal to this thread
636 	 * to get it out of some blocking network function.
637 	 * Clear signals; otherwise kthread_run(), which internally uses
638 	 * wait_on_completion_killable(), will mistake our pending signal
639 	 * for a new fatal signal and fail. */
640 	flush_signals(current);
641 	opa = kthread_run(_try_outdate_peer_async, connection, "drbd_async_h");
642 	if (IS_ERR(opa)) {
643 		drbd_err(connection, "out of mem, failed to invoke fence-peer helper\n");
644 		kref_put(&connection->kref, drbd_destroy_connection);
645 	}
646 }
647 
648 enum drbd_state_rv
649 drbd_set_role(struct drbd_device *const device, enum drbd_role new_role, int force)
650 {
651 	struct drbd_peer_device *const peer_device = first_peer_device(device);
652 	struct drbd_connection *const connection = peer_device ? peer_device->connection : NULL;
653 	const int max_tries = 4;
654 	enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
655 	struct net_conf *nc;
656 	int try = 0;
657 	int forced = 0;
658 	union drbd_state mask, val;
659 
660 	if (new_role == R_PRIMARY) {
661 		struct drbd_connection *connection;
662 
663 		/* Detect dead peers as soon as possible.  */
664 
665 		rcu_read_lock();
666 		for_each_connection(connection, device->resource)
667 			request_ping(connection);
668 		rcu_read_unlock();
669 	}
670 
671 	mutex_lock(device->state_mutex);
672 
673 	mask.i = 0; mask.role = R_MASK;
674 	val.i  = 0; val.role  = new_role;
675 
676 	while (try++ < max_tries) {
677 		rv = _drbd_request_state_holding_state_mutex(device, mask, val, CS_WAIT_COMPLETE);
678 
679 		/* in case we first succeeded to outdate,
680 		 * but now suddenly could establish a connection */
681 		if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
682 			val.pdsk = 0;
683 			mask.pdsk = 0;
684 			continue;
685 		}
686 
687 		if (rv == SS_NO_UP_TO_DATE_DISK && force &&
688 		    (device->state.disk < D_UP_TO_DATE &&
689 		     device->state.disk >= D_INCONSISTENT)) {
690 			mask.disk = D_MASK;
691 			val.disk  = D_UP_TO_DATE;
692 			forced = 1;
693 			continue;
694 		}
695 
696 		if (rv == SS_NO_UP_TO_DATE_DISK &&
697 		    device->state.disk == D_CONSISTENT && mask.pdsk == 0) {
698 			D_ASSERT(device, device->state.pdsk == D_UNKNOWN);
699 
700 			if (conn_try_outdate_peer(connection)) {
701 				val.disk = D_UP_TO_DATE;
702 				mask.disk = D_MASK;
703 			}
704 			continue;
705 		}
706 
707 		if (rv == SS_NOTHING_TO_DO)
708 			goto out;
709 		if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
710 			if (!conn_try_outdate_peer(connection) && force) {
711 				drbd_warn(device, "Forced into split brain situation!\n");
712 				mask.pdsk = D_MASK;
713 				val.pdsk  = D_OUTDATED;
714 
715 			}
716 			continue;
717 		}
718 		if (rv == SS_TWO_PRIMARIES) {
719 			/* Maybe the peer is detected as dead very soon...
720 			   retry at most once more in this case. */
721 			if (try < max_tries) {
722 				int timeo;
723 				try = max_tries - 1;
724 				rcu_read_lock();
725 				nc = rcu_dereference(connection->net_conf);
726 				timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
727 				rcu_read_unlock();
728 				schedule_timeout_interruptible(timeo);
729 			}
730 			continue;
731 		}
732 		if (rv < SS_SUCCESS) {
733 			rv = _drbd_request_state(device, mask, val,
734 						CS_VERBOSE + CS_WAIT_COMPLETE);
735 			if (rv < SS_SUCCESS)
736 				goto out;
737 		}
738 		break;
739 	}
740 
741 	if (rv < SS_SUCCESS)
742 		goto out;
743 
744 	if (forced)
745 		drbd_warn(device, "Forced to consider local data as UpToDate!\n");
746 
747 	/* Wait until nothing is on the fly :) */
748 	wait_event(device->misc_wait, atomic_read(&device->ap_pending_cnt) == 0);
749 
750 	/* FIXME also wait for all pending P_BARRIER_ACK? */
751 
752 	if (new_role == R_SECONDARY) {
753 		if (get_ldev(device)) {
754 			device->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
755 			put_ldev(device);
756 		}
757 	} else {
758 		mutex_lock(&device->resource->conf_update);
759 		nc = connection->net_conf;
760 		if (nc)
761 			nc->discard_my_data = 0; /* without copy; single bit op is atomic */
762 		mutex_unlock(&device->resource->conf_update);
763 
764 		if (get_ldev(device)) {
765 			if (((device->state.conn < C_CONNECTED ||
766 			       device->state.pdsk <= D_FAILED)
767 			      && device->ldev->md.uuid[UI_BITMAP] == 0) || forced)
768 				drbd_uuid_new_current(device);
769 
770 			device->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
771 			put_ldev(device);
772 		}
773 	}
774 
775 	/* writeout of activity log covered areas of the bitmap
776 	 * to stable storage done in after state change already */
777 
778 	if (device->state.conn >= C_WF_REPORT_PARAMS) {
779 		/* if this was forced, we should consider sync */
780 		if (forced)
781 			drbd_send_uuids(peer_device);
782 		drbd_send_current_state(peer_device);
783 	}
784 
785 	drbd_md_sync(device);
786 	set_disk_ro(device->vdisk, new_role == R_SECONDARY);
787 	kobject_uevent(&disk_to_dev(device->vdisk)->kobj, KOBJ_CHANGE);
788 out:
789 	mutex_unlock(device->state_mutex);
790 	return rv;
791 }
792 
793 static const char *from_attrs_err_to_txt(int err)
794 {
795 	return	err == -ENOMSG ? "required attribute missing" :
796 		err == -EEXIST ? "can not change invariant setting" :
797 		"invalid attribute value";
798 }
799 
800 static int drbd_nl_set_role(struct sk_buff *skb, struct genl_info *info)
801 {
802 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
803 	struct set_role_parms parms;
804 	int err;
805 	enum drbd_ret_code retcode;
806 	enum drbd_state_rv rv;
807 
808 	if (!adm_ctx->reply_skb)
809 		return 0;
810 	retcode = adm_ctx->reply_dh->ret_code;
811 	if (retcode != NO_ERROR)
812 		goto out;
813 
814 	memset(&parms, 0, sizeof(parms));
815 	if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
816 		err = set_role_parms_from_attrs(&parms, info);
817 		if (err) {
818 			retcode = ERR_MANDATORY_TAG;
819 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
820 			goto out;
821 		}
822 	}
823 	genl_unlock();
824 	mutex_lock(&adm_ctx->resource->adm_mutex);
825 
826 	if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
827 		rv = drbd_set_role(adm_ctx->device, R_PRIMARY, parms.assume_uptodate);
828 	else
829 		rv = drbd_set_role(adm_ctx->device, R_SECONDARY, 0);
830 
831 	mutex_unlock(&adm_ctx->resource->adm_mutex);
832 	genl_lock();
833 	adm_ctx->reply_dh->ret_code = rv;
834 	return 0;
835 out:
836 	adm_ctx->reply_dh->ret_code = retcode;
837 	return 0;
838 }
839 
840 int drbd_nl_primary_doit(struct sk_buff *skb, struct genl_info *info)
841 {
842 	return drbd_nl_set_role(skb, info);
843 }
844 
845 int drbd_nl_secondary_doit(struct sk_buff *skb, struct genl_info *info)
846 {
847 	return drbd_nl_set_role(skb, info);
848 }
849 
850 /* Initializes the md.*_offset members, so we are able to find
851  * the on disk meta data.
852  *
853  * We currently have two possible layouts:
854  * external:
855  *   |----------- md_size_sect ------------------|
856  *   [ 4k superblock ][ activity log ][  Bitmap  ]
857  *   | al_offset == 8 |
858  *   | bm_offset = al_offset + X      |
859  *  ==> bitmap sectors = md_size_sect - bm_offset
860  *
861  * internal:
862  *            |----------- md_size_sect ------------------|
863  * [data.....][  Bitmap  ][ activity log ][ 4k superblock ]
864  *                        | al_offset < 0 |
865  *            | bm_offset = al_offset - Y |
866  *  ==> bitmap sectors = Y = al_offset - bm_offset
867  *
868  *  Activity log size used to be fixed 32kB,
869  *  but is about to become configurable.
870  */
871 static void drbd_md_set_sector_offsets(struct drbd_device *device,
872 				       struct drbd_backing_dev *bdev)
873 {
874 	sector_t md_size_sect = 0;
875 	unsigned int al_size_sect = bdev->md.al_size_4k * 8;
876 
877 	bdev->md.md_offset = drbd_md_ss(bdev);
878 
879 	switch (bdev->md.meta_dev_idx) {
880 	default:
881 		/* v07 style fixed size indexed meta data */
882 		bdev->md.md_size_sect = MD_128MB_SECT;
883 		bdev->md.al_offset = MD_4kB_SECT;
884 		bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
885 		break;
886 	case DRBD_MD_INDEX_FLEX_EXT:
887 		/* just occupy the full device; unit: sectors */
888 		bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
889 		bdev->md.al_offset = MD_4kB_SECT;
890 		bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
891 		break;
892 	case DRBD_MD_INDEX_INTERNAL:
893 	case DRBD_MD_INDEX_FLEX_INT:
894 		/* al size is still fixed */
895 		bdev->md.al_offset = -al_size_sect;
896 		/* we need (slightly less than) ~ this much bitmap sectors: */
897 		md_size_sect = drbd_get_capacity(bdev->backing_bdev);
898 		md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
899 		md_size_sect = BM_SECT_TO_EXT(md_size_sect);
900 		md_size_sect = ALIGN(md_size_sect, 8);
901 
902 		/* plus the "drbd meta data super block",
903 		 * and the activity log; */
904 		md_size_sect += MD_4kB_SECT + al_size_sect;
905 
906 		bdev->md.md_size_sect = md_size_sect;
907 		/* bitmap offset is adjusted by 'super' block size */
908 		bdev->md.bm_offset   = -md_size_sect + MD_4kB_SECT;
909 		break;
910 	}
911 }
912 
913 /* input size is expected to be in KB */
914 char *ppsize(char *buf, unsigned long long size)
915 {
916 	/* Needs 9 bytes at max including trailing NUL:
917 	 * -1ULL ==> "16384 EB" */
918 	static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
919 	int base = 0;
920 	while (size >= 10000 && base < sizeof(units)-1) {
921 		/* shift + round */
922 		size = (size >> 10) + !!(size & (1<<9));
923 		base++;
924 	}
925 	sprintf(buf, "%u %cB", (unsigned)size, units[base]);
926 
927 	return buf;
928 }
929 
930 /* there is still a theoretical deadlock when called from receiver
931  * on an D_INCONSISTENT R_PRIMARY:
932  *  remote READ does inc_ap_bio, receiver would need to receive answer
933  *  packet from remote to dec_ap_bio again.
934  *  receiver receive_sizes(), comes here,
935  *  waits for ap_bio_cnt == 0. -> deadlock.
936  * but this cannot happen, actually, because:
937  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
938  *  (not connected, or bad/no disk on peer):
939  *  see drbd_fail_request_early, ap_bio_cnt is zero.
940  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
941  *  peer may not initiate a resize.
942  */
943 /* Note these are not to be confused with
944  * drbd_nl_suspend_io_doit/drbd_nl_resume_io_doit,
945  * which are (sub) state changes triggered by admin (drbdsetup),
946  * and can be long lived.
947  * This changes an device->flag, is triggered by drbd internals,
948  * and should be short-lived. */
949 /* It needs to be a counter, since multiple threads might
950    independently suspend and resume IO. */
951 void drbd_suspend_io(struct drbd_device *device)
952 {
953 	atomic_inc(&device->suspend_cnt);
954 	if (drbd_suspended(device))
955 		return;
956 	wait_event(device->misc_wait, !atomic_read(&device->ap_bio_cnt));
957 }
958 
959 void drbd_resume_io(struct drbd_device *device)
960 {
961 	if (atomic_dec_and_test(&device->suspend_cnt))
962 		wake_up(&device->misc_wait);
963 }
964 
965 /*
966  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
967  * @device:	DRBD device.
968  *
969  * Returns 0 on success, negative return values indicate errors.
970  * You should call drbd_md_sync() after calling this function.
971  */
972 enum determine_dev_size
973 drbd_determine_dev_size(struct drbd_device *device, enum dds_flags flags, struct resize_parms *rs) __must_hold(local)
974 {
975 	struct md_offsets_and_sizes {
976 		u64 last_agreed_sect;
977 		u64 md_offset;
978 		s32 al_offset;
979 		s32 bm_offset;
980 		u32 md_size_sect;
981 
982 		u32 al_stripes;
983 		u32 al_stripe_size_4k;
984 	} prev;
985 	sector_t u_size, size;
986 	struct drbd_md *md = &device->ldev->md;
987 	void *buffer;
988 
989 	int md_moved, la_size_changed;
990 	enum determine_dev_size rv = DS_UNCHANGED;
991 
992 	/* We may change the on-disk offsets of our meta data below.  Lock out
993 	 * anything that may cause meta data IO, to avoid acting on incomplete
994 	 * layout changes or scribbling over meta data that is in the process
995 	 * of being moved.
996 	 *
997 	 * Move is not exactly correct, btw, currently we have all our meta
998 	 * data in core memory, to "move" it we just write it all out, there
999 	 * are no reads. */
1000 	drbd_suspend_io(device);
1001 	buffer = drbd_md_get_buffer(device, __func__); /* Lock meta-data IO */
1002 	if (!buffer) {
1003 		drbd_resume_io(device);
1004 		return DS_ERROR;
1005 	}
1006 
1007 	/* remember current offset and sizes */
1008 	prev.last_agreed_sect = md->la_size_sect;
1009 	prev.md_offset = md->md_offset;
1010 	prev.al_offset = md->al_offset;
1011 	prev.bm_offset = md->bm_offset;
1012 	prev.md_size_sect = md->md_size_sect;
1013 	prev.al_stripes = md->al_stripes;
1014 	prev.al_stripe_size_4k = md->al_stripe_size_4k;
1015 
1016 	if (rs) {
1017 		/* rs is non NULL if we should change the AL layout only */
1018 		md->al_stripes = rs->al_stripes;
1019 		md->al_stripe_size_4k = rs->al_stripe_size / 4;
1020 		md->al_size_4k = (u64)rs->al_stripes * rs->al_stripe_size / 4;
1021 	}
1022 
1023 	drbd_md_set_sector_offsets(device, device->ldev);
1024 
1025 	rcu_read_lock();
1026 	u_size = rcu_dereference(device->ldev->disk_conf)->disk_size;
1027 	rcu_read_unlock();
1028 	size = drbd_new_dev_size(device, device->ldev, u_size, flags & DDSF_FORCED);
1029 
1030 	if (size < prev.last_agreed_sect) {
1031 		if (rs && u_size == 0) {
1032 			/* Remove "rs &&" later. This check should always be active, but
1033 			   right now the receiver expects the permissive behavior */
1034 			drbd_warn(device, "Implicit shrink not allowed. "
1035 				 "Use --size=%llus for explicit shrink.\n",
1036 				 (unsigned long long)size);
1037 			rv = DS_ERROR_SHRINK;
1038 		}
1039 		if (u_size > size)
1040 			rv = DS_ERROR_SPACE_MD;
1041 		if (rv != DS_UNCHANGED)
1042 			goto err_out;
1043 	}
1044 
1045 	if (get_capacity(device->vdisk) != size ||
1046 	    drbd_bm_capacity(device) != size) {
1047 		int err;
1048 		err = drbd_bm_resize(device, size, !(flags & DDSF_NO_RESYNC));
1049 		if (unlikely(err)) {
1050 			/* currently there is only one error: ENOMEM! */
1051 			size = drbd_bm_capacity(device);
1052 			if (size == 0) {
1053 				drbd_err(device, "OUT OF MEMORY! "
1054 				    "Could not allocate bitmap!\n");
1055 			} else {
1056 				drbd_err(device, "BM resizing failed. "
1057 				    "Leaving size unchanged\n");
1058 			}
1059 			rv = DS_ERROR;
1060 		}
1061 		/* racy, see comments above. */
1062 		drbd_set_my_capacity(device, size);
1063 		md->la_size_sect = size;
1064 	}
1065 	if (rv <= DS_ERROR)
1066 		goto err_out;
1067 
1068 	la_size_changed = (prev.last_agreed_sect != md->la_size_sect);
1069 
1070 	md_moved = prev.md_offset    != md->md_offset
1071 		|| prev.md_size_sect != md->md_size_sect;
1072 
1073 	if (la_size_changed || md_moved || rs) {
1074 		u32 prev_flags;
1075 
1076 		/* We do some synchronous IO below, which may take some time.
1077 		 * Clear the timer, to avoid scary "timer expired!" messages,
1078 		 * "Superblock" is written out at least twice below, anyways. */
1079 		timer_delete(&device->md_sync_timer);
1080 
1081 		/* We won't change the "al-extents" setting, we just may need
1082 		 * to move the on-disk location of the activity log ringbuffer.
1083 		 * Lock for transaction is good enough, it may well be "dirty"
1084 		 * or even "starving". */
1085 		wait_event(device->al_wait, lc_try_lock_for_transaction(device->act_log));
1086 
1087 		/* mark current on-disk bitmap and activity log as unreliable */
1088 		prev_flags = md->flags;
1089 		md->flags |= MDF_FULL_SYNC | MDF_AL_DISABLED;
1090 		drbd_md_write(device, buffer);
1091 
1092 		drbd_al_initialize(device, buffer);
1093 
1094 		drbd_info(device, "Writing the whole bitmap, %s\n",
1095 			 la_size_changed && md_moved ? "size changed and md moved" :
1096 			 la_size_changed ? "size changed" : "md moved");
1097 		/* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
1098 		drbd_bitmap_io(device, md_moved ? &drbd_bm_write_all : &drbd_bm_write,
1099 			       "size changed", BM_LOCKED_MASK, NULL);
1100 
1101 		/* on-disk bitmap and activity log is authoritative again
1102 		 * (unless there was an IO error meanwhile...) */
1103 		md->flags = prev_flags;
1104 		drbd_md_write(device, buffer);
1105 
1106 		if (rs)
1107 			drbd_info(device, "Changed AL layout to al-stripes = %d, al-stripe-size-kB = %d\n",
1108 				  md->al_stripes, md->al_stripe_size_4k * 4);
1109 	}
1110 
1111 	if (size > prev.last_agreed_sect)
1112 		rv = prev.last_agreed_sect ? DS_GREW : DS_GREW_FROM_ZERO;
1113 	if (size < prev.last_agreed_sect)
1114 		rv = DS_SHRUNK;
1115 
1116 	if (0) {
1117 	err_out:
1118 		/* restore previous offset and sizes */
1119 		md->la_size_sect = prev.last_agreed_sect;
1120 		md->md_offset = prev.md_offset;
1121 		md->al_offset = prev.al_offset;
1122 		md->bm_offset = prev.bm_offset;
1123 		md->md_size_sect = prev.md_size_sect;
1124 		md->al_stripes = prev.al_stripes;
1125 		md->al_stripe_size_4k = prev.al_stripe_size_4k;
1126 		md->al_size_4k = (u64)prev.al_stripes * prev.al_stripe_size_4k;
1127 	}
1128 	lc_unlock(device->act_log);
1129 	wake_up(&device->al_wait);
1130 	drbd_md_put_buffer(device);
1131 	drbd_resume_io(device);
1132 
1133 	return rv;
1134 }
1135 
1136 sector_t
1137 drbd_new_dev_size(struct drbd_device *device, struct drbd_backing_dev *bdev,
1138 		  sector_t u_size, int assume_peer_has_space)
1139 {
1140 	sector_t p_size = device->p_size;   /* partner's disk size. */
1141 	sector_t la_size_sect = bdev->md.la_size_sect; /* last agreed size. */
1142 	sector_t m_size; /* my size */
1143 	sector_t size = 0;
1144 
1145 	m_size = drbd_get_max_capacity(bdev);
1146 
1147 	if (device->state.conn < C_CONNECTED && assume_peer_has_space) {
1148 		drbd_warn(device, "Resize while not connected was forced by the user!\n");
1149 		p_size = m_size;
1150 	}
1151 
1152 	if (p_size && m_size) {
1153 		size = min_t(sector_t, p_size, m_size);
1154 	} else {
1155 		if (la_size_sect) {
1156 			size = la_size_sect;
1157 			if (m_size && m_size < size)
1158 				size = m_size;
1159 			if (p_size && p_size < size)
1160 				size = p_size;
1161 		} else {
1162 			if (m_size)
1163 				size = m_size;
1164 			if (p_size)
1165 				size = p_size;
1166 		}
1167 	}
1168 
1169 	if (size == 0)
1170 		drbd_err(device, "Both nodes diskless!\n");
1171 
1172 	if (u_size) {
1173 		if (u_size > size)
1174 			drbd_err(device, "Requested disk size is too big (%lu > %lu)\n",
1175 			    (unsigned long)u_size>>1, (unsigned long)size>>1);
1176 		else
1177 			size = u_size;
1178 	}
1179 
1180 	return size;
1181 }
1182 
1183 /*
1184  * drbd_check_al_size() - Ensures that the AL is of the right size
1185  * @device:	DRBD device.
1186  *
1187  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
1188  * failed, and 0 on success. You should call drbd_md_sync() after you called
1189  * this function.
1190  */
1191 static int drbd_check_al_size(struct drbd_device *device, struct disk_conf *dc)
1192 {
1193 	struct lru_cache *n, *t;
1194 	struct lc_element *e;
1195 	unsigned int in_use;
1196 	int i;
1197 
1198 	if (device->act_log &&
1199 	    device->act_log->nr_elements == dc->al_extents)
1200 		return 0;
1201 
1202 	in_use = 0;
1203 	t = device->act_log;
1204 	n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
1205 		dc->al_extents, sizeof(struct lc_element), 0);
1206 
1207 	if (n == NULL) {
1208 		drbd_err(device, "Cannot allocate act_log lru!\n");
1209 		return -ENOMEM;
1210 	}
1211 	spin_lock_irq(&device->al_lock);
1212 	if (t) {
1213 		for (i = 0; i < t->nr_elements; i++) {
1214 			e = lc_element_by_index(t, i);
1215 			if (e->refcnt)
1216 				drbd_err(device, "refcnt(%d)==%d\n",
1217 				    e->lc_number, e->refcnt);
1218 			in_use += e->refcnt;
1219 		}
1220 	}
1221 	if (!in_use)
1222 		device->act_log = n;
1223 	spin_unlock_irq(&device->al_lock);
1224 	if (in_use) {
1225 		drbd_err(device, "Activity log still in use!\n");
1226 		lc_destroy(n);
1227 		return -EBUSY;
1228 	} else {
1229 		lc_destroy(t);
1230 	}
1231 	drbd_md_mark_dirty(device); /* we changed device->act_log->nr_elemens */
1232 	return 0;
1233 }
1234 
1235 static unsigned int drbd_max_peer_bio_size(struct drbd_device *device)
1236 {
1237 	/*
1238 	 * We may ignore peer limits if the peer is modern enough.  From 8.3.8
1239 	 * onwards the peer can use multiple BIOs for a single peer_request.
1240 	 */
1241 	if (device->state.conn < C_WF_REPORT_PARAMS)
1242 		return device->peer_max_bio_size;
1243 
1244 	if (first_peer_device(device)->connection->agreed_pro_version < 94)
1245 		return min(device->peer_max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
1246 
1247 	/*
1248 	 * Correct old drbd (up to 8.3.7) if it believes it can do more than
1249 	 * 32KiB.
1250 	 */
1251 	if (first_peer_device(device)->connection->agreed_pro_version == 94)
1252 		return DRBD_MAX_SIZE_H80_PACKET;
1253 
1254 	/*
1255 	 * drbd 8.3.8 onwards, before 8.4.0
1256 	 */
1257 	if (first_peer_device(device)->connection->agreed_pro_version < 100)
1258 		return DRBD_MAX_BIO_SIZE_P95;
1259 	return DRBD_MAX_BIO_SIZE;
1260 }
1261 
1262 static unsigned int drbd_max_discard_sectors(struct drbd_connection *connection)
1263 {
1264 	/* when we introduced REQ_WRITE_SAME support, we also bumped
1265 	 * our maximum supported batch bio size used for discards. */
1266 	if (connection->agreed_features & DRBD_FF_WSAME)
1267 		return DRBD_MAX_BBIO_SECTORS;
1268 	/* before, with DRBD <= 8.4.6, we only allowed up to one AL_EXTENT_SIZE. */
1269 	return AL_EXTENT_SIZE >> 9;
1270 }
1271 
1272 static bool drbd_discard_supported(struct drbd_connection *connection,
1273 		struct drbd_backing_dev *bdev)
1274 {
1275 	if (bdev && !bdev_max_discard_sectors(bdev->backing_bdev))
1276 		return false;
1277 
1278 	if (connection->cstate >= C_CONNECTED &&
1279 	    !(connection->agreed_features & DRBD_FF_TRIM)) {
1280 		drbd_info(connection,
1281 			"peer DRBD too old, does not support TRIM: disabling discards\n");
1282 		return false;
1283 	}
1284 
1285 	return true;
1286 }
1287 
1288 /* This is the workaround for "bio would need to, but cannot, be split" */
1289 static unsigned int drbd_backing_dev_max_segments(struct drbd_device *device)
1290 {
1291 	unsigned int max_segments;
1292 
1293 	rcu_read_lock();
1294 	max_segments = rcu_dereference(device->ldev->disk_conf)->max_bio_bvecs;
1295 	rcu_read_unlock();
1296 
1297 	if (!max_segments)
1298 		return BLK_MAX_SEGMENTS;
1299 	return max_segments;
1300 }
1301 
1302 void drbd_reconsider_queue_parameters(struct drbd_device *device,
1303 		struct drbd_backing_dev *bdev, struct o_qlim *o)
1304 {
1305 	struct drbd_connection *connection =
1306 		first_peer_device(device)->connection;
1307 	struct request_queue * const q = device->rq_queue;
1308 	unsigned int now = queue_max_hw_sectors(q) << 9;
1309 	struct queue_limits lim;
1310 	struct request_queue *b = NULL;
1311 	unsigned int new;
1312 
1313 	if (bdev) {
1314 		b = bdev->backing_bdev->bd_disk->queue;
1315 
1316 		device->local_max_bio_size =
1317 			queue_max_hw_sectors(b) << SECTOR_SHIFT;
1318 	}
1319 
1320 	/*
1321 	 * We may later detach and re-attach on a disconnected Primary.  Avoid
1322 	 * decreasing the value in this case.
1323 	 *
1324 	 * We want to store what we know the peer DRBD can handle, not what the
1325 	 * peer IO backend can handle.
1326 	 */
1327 	new = min3(DRBD_MAX_BIO_SIZE, device->local_max_bio_size,
1328 		max(drbd_max_peer_bio_size(device), device->peer_max_bio_size));
1329 	if (new != now) {
1330 		if (device->state.role == R_PRIMARY && new < now)
1331 			drbd_err(device, "ASSERT FAILED new < now; (%u < %u)\n",
1332 					new, now);
1333 		drbd_info(device, "max BIO size = %u\n", new);
1334 	}
1335 
1336 	lim = queue_limits_start_update(q);
1337 	if (bdev) {
1338 		blk_set_stacking_limits(&lim);
1339 		lim.max_segments = drbd_backing_dev_max_segments(device);
1340 	} else {
1341 		lim.max_segments = BLK_MAX_SEGMENTS;
1342 		lim.features = BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA |
1343 			       BLK_FEAT_ROTATIONAL | BLK_FEAT_STABLE_WRITES;
1344 	}
1345 
1346 	lim.max_hw_sectors = new >> SECTOR_SHIFT;
1347 	lim.seg_boundary_mask = PAGE_SIZE - 1;
1348 
1349 	/*
1350 	 * We don't care for the granularity, really.
1351 	 *
1352 	 * Stacking limits below should fix it for the local device.  Whether or
1353 	 * not it is a suitable granularity on the remote device is not our
1354 	 * problem, really. If you care, you need to use devices with similar
1355 	 * topology on all peers.
1356 	 */
1357 	if (drbd_discard_supported(connection, bdev)) {
1358 		lim.discard_granularity = 512;
1359 		lim.max_hw_discard_sectors =
1360 			drbd_max_discard_sectors(connection);
1361 	} else {
1362 		lim.discard_granularity = 0;
1363 		lim.max_hw_discard_sectors = 0;
1364 	}
1365 
1366 	if (bdev) {
1367 		blk_stack_limits(&lim, &b->limits, 0);
1368 		/*
1369 		 * blk_set_stacking_limits() cleared the features, and
1370 		 * blk_stack_limits() may or may not have inherited
1371 		 * BLK_FEAT_STABLE_WRITES from the backing device.
1372 		 *
1373 		 * DRBD always requires stable writes because:
1374 		 * 1. The same bio data is read for both local disk I/O and
1375 		 *    network transmission. If the page changes mid-flight,
1376 		 *    the local and remote copies could diverge.
1377 		 * 2. When data integrity is enabled, DRBD calculates a
1378 		 *    checksum before sending the data. If the page changes
1379 		 *    between checksum calculation and transmission, the
1380 		 *    receiver will detect a checksum mismatch.
1381 		 */
1382 		lim.features |= BLK_FEAT_STABLE_WRITES;
1383 	}
1384 
1385 	/*
1386 	 * If we can handle "zeroes" efficiently on the protocol, we want to do
1387 	 * that, even if our backend does not announce max_write_zeroes_sectors
1388 	 * itself.
1389 	 */
1390 	if (connection->agreed_features & DRBD_FF_WZEROES)
1391 		lim.max_write_zeroes_sectors = DRBD_MAX_BBIO_SECTORS;
1392 	else
1393 		lim.max_write_zeroes_sectors = 0;
1394 	lim.max_hw_wzeroes_unmap_sectors = 0;
1395 
1396 	if ((lim.discard_granularity >> SECTOR_SHIFT) >
1397 	    lim.max_hw_discard_sectors) {
1398 		lim.discard_granularity = 0;
1399 		lim.max_hw_discard_sectors = 0;
1400 	}
1401 
1402 	if (queue_limits_commit_update(q, &lim))
1403 		drbd_err(device, "setting new queue limits failed\n");
1404 }
1405 
1406 /* Starts the worker thread */
1407 static void conn_reconfig_start(struct drbd_connection *connection)
1408 {
1409 	drbd_thread_start(&connection->worker);
1410 	drbd_flush_workqueue(&connection->sender_work);
1411 }
1412 
1413 /* if still unconfigured, stops worker again. */
1414 static void conn_reconfig_done(struct drbd_connection *connection)
1415 {
1416 	bool stop_threads;
1417 	spin_lock_irq(&connection->resource->req_lock);
1418 	stop_threads = conn_all_vols_unconf(connection) &&
1419 		connection->cstate == C_STANDALONE;
1420 	spin_unlock_irq(&connection->resource->req_lock);
1421 	if (stop_threads) {
1422 		/* ack_receiver thread and ack_sender workqueue are implicitly
1423 		 * stopped by receiver in conn_disconnect() */
1424 		drbd_thread_stop(&connection->receiver);
1425 		drbd_thread_stop(&connection->worker);
1426 	}
1427 }
1428 
1429 /* Make sure IO is suspended before calling this function(). */
1430 static void drbd_suspend_al(struct drbd_device *device)
1431 {
1432 	int s = 0;
1433 
1434 	if (!lc_try_lock(device->act_log)) {
1435 		drbd_warn(device, "Failed to lock al in drbd_suspend_al()\n");
1436 		return;
1437 	}
1438 
1439 	drbd_al_shrink(device);
1440 	spin_lock_irq(&device->resource->req_lock);
1441 	if (device->state.conn < C_CONNECTED)
1442 		s = !test_and_set_bit(AL_SUSPENDED, &device->flags);
1443 	spin_unlock_irq(&device->resource->req_lock);
1444 	lc_unlock(device->act_log);
1445 
1446 	if (s)
1447 		drbd_info(device, "Suspended AL updates\n");
1448 }
1449 
1450 
1451 static bool should_set_defaults(struct genl_info *info)
1452 {
1453 	struct drbd_genlmsghdr *dh = genl_info_userhdr(info);
1454 
1455 	return 0 != (dh->flags & DRBD_GENL_F_SET_DEFAULTS);
1456 }
1457 
1458 static unsigned int drbd_al_extents_max(struct drbd_backing_dev *bdev)
1459 {
1460 	/* This is limited by 16 bit "slot" numbers,
1461 	 * and by available on-disk context storage.
1462 	 *
1463 	 * Also (u16)~0 is special (denotes a "free" extent).
1464 	 *
1465 	 * One transaction occupies one 4kB on-disk block,
1466 	 * we have n such blocks in the on disk ring buffer,
1467 	 * the "current" transaction may fail (n-1),
1468 	 * and there is 919 slot numbers context information per transaction.
1469 	 *
1470 	 * 72 transaction blocks amounts to more than 2**16 context slots,
1471 	 * so cap there first.
1472 	 */
1473 	const unsigned int max_al_nr = DRBD_AL_EXTENTS_MAX;
1474 	const unsigned int sufficient_on_disk =
1475 		(max_al_nr + AL_CONTEXT_PER_TRANSACTION -1)
1476 		/AL_CONTEXT_PER_TRANSACTION;
1477 
1478 	unsigned int al_size_4k = bdev->md.al_size_4k;
1479 
1480 	if (al_size_4k > sufficient_on_disk)
1481 		return max_al_nr;
1482 
1483 	return (al_size_4k - 1) * AL_CONTEXT_PER_TRANSACTION;
1484 }
1485 
1486 static bool write_ordering_changed(struct disk_conf *a, struct disk_conf *b)
1487 {
1488 	return	a->disk_barrier != b->disk_barrier ||
1489 		a->disk_flushes != b->disk_flushes ||
1490 		a->disk_drain != b->disk_drain;
1491 }
1492 
1493 static void sanitize_disk_conf(struct drbd_device *device, struct disk_conf *disk_conf,
1494 			       struct drbd_backing_dev *nbc)
1495 {
1496 	struct block_device *bdev = nbc->backing_bdev;
1497 
1498 	if (disk_conf->al_extents < DRBD_AL_EXTENTS_MIN)
1499 		disk_conf->al_extents = DRBD_AL_EXTENTS_MIN;
1500 	if (disk_conf->al_extents > drbd_al_extents_max(nbc))
1501 		disk_conf->al_extents = drbd_al_extents_max(nbc);
1502 
1503 	if (!bdev_max_discard_sectors(bdev)) {
1504 		if (disk_conf->rs_discard_granularity) {
1505 			disk_conf->rs_discard_granularity = 0; /* disable feature */
1506 			drbd_info(device, "rs_discard_granularity feature disabled\n");
1507 		}
1508 	}
1509 
1510 	if (disk_conf->rs_discard_granularity) {
1511 		int orig_value = disk_conf->rs_discard_granularity;
1512 		sector_t discard_size = bdev_max_discard_sectors(bdev) << 9;
1513 		unsigned int discard_granularity = bdev_discard_granularity(bdev);
1514 		int remainder;
1515 
1516 		if (discard_granularity > disk_conf->rs_discard_granularity)
1517 			disk_conf->rs_discard_granularity = discard_granularity;
1518 
1519 		remainder = disk_conf->rs_discard_granularity %
1520 				discard_granularity;
1521 		disk_conf->rs_discard_granularity += remainder;
1522 
1523 		if (disk_conf->rs_discard_granularity > discard_size)
1524 			disk_conf->rs_discard_granularity = discard_size;
1525 
1526 		if (disk_conf->rs_discard_granularity != orig_value)
1527 			drbd_info(device, "rs_discard_granularity changed to %d\n",
1528 				  disk_conf->rs_discard_granularity);
1529 	}
1530 }
1531 
1532 static int disk_opts_check_al_size(struct drbd_device *device, struct disk_conf *dc)
1533 {
1534 	int err = -EBUSY;
1535 
1536 	if (device->act_log &&
1537 	    device->act_log->nr_elements == dc->al_extents)
1538 		return 0;
1539 
1540 	drbd_suspend_io(device);
1541 	/* If IO completion is currently blocked, we would likely wait
1542 	 * "forever" for the activity log to become unused. So we don't. */
1543 	if (atomic_read(&device->ap_bio_cnt))
1544 		goto out;
1545 
1546 	wait_event(device->al_wait, lc_try_lock(device->act_log));
1547 	drbd_al_shrink(device);
1548 	err = drbd_check_al_size(device, dc);
1549 	lc_unlock(device->act_log);
1550 	wake_up(&device->al_wait);
1551 out:
1552 	drbd_resume_io(device);
1553 	return err;
1554 }
1555 
1556 int drbd_nl_chg_disk_opts_doit(struct sk_buff *skb, struct genl_info *info)
1557 {
1558 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
1559 	enum drbd_ret_code retcode;
1560 	struct drbd_device *device;
1561 	struct disk_conf *new_disk_conf, *old_disk_conf;
1562 	struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1563 	struct nlattr **ntb;
1564 	int err;
1565 	unsigned int fifo_size;
1566 
1567 	if (!adm_ctx->reply_skb)
1568 		return 0;
1569 	retcode = adm_ctx->reply_dh->ret_code;
1570 	if (retcode != NO_ERROR)
1571 		goto finish;
1572 
1573 	device = adm_ctx->device;
1574 	mutex_lock(&adm_ctx->resource->adm_mutex);
1575 
1576 	/* we also need a disk
1577 	 * to change the options on */
1578 	if (!get_ldev(device)) {
1579 		retcode = ERR_NO_DISK;
1580 		goto out;
1581 	}
1582 
1583 	new_disk_conf = kmalloc_obj(struct disk_conf);
1584 	if (!new_disk_conf) {
1585 		retcode = ERR_NOMEM;
1586 		goto fail;
1587 	}
1588 
1589 	mutex_lock(&device->resource->conf_update);
1590 	old_disk_conf = device->ldev->disk_conf;
1591 	*new_disk_conf = *old_disk_conf;
1592 	if (should_set_defaults(info))
1593 		set_disk_conf_defaults(new_disk_conf);
1594 
1595 	err = disk_conf_from_attrs(new_disk_conf, info);
1596 	if (err && err != -ENOMSG) {
1597 		retcode = ERR_MANDATORY_TAG;
1598 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
1599 		goto fail_unlock;
1600 	}
1601 
1602 	err = disk_conf_ntb_from_attrs(&ntb, info);
1603 	if (!err) {
1604 		if (has_invariant(ntb, DRBD_A_DISK_CONF_BACKING_DEV) ||
1605 		    has_invariant(ntb, DRBD_A_DISK_CONF_META_DEV) ||
1606 		    has_invariant(ntb, DRBD_A_DISK_CONF_META_DEV_IDX) ||
1607 		    has_invariant(ntb, DRBD_A_DISK_CONF_DISK_SIZE) ||
1608 		    has_invariant(ntb, DRBD_A_DISK_CONF_MAX_BIO_BVECS)) {
1609 			retcode = ERR_MANDATORY_TAG;
1610 			drbd_msg_put_info(adm_ctx->reply_skb,
1611 				"cannot change invariant setting");
1612 			kfree(ntb);
1613 			goto fail_unlock;
1614 		}
1615 		kfree(ntb);
1616 	}
1617 
1618 	if (!expect(device, new_disk_conf->resync_rate >= 1))
1619 		new_disk_conf->resync_rate = 1;
1620 
1621 	sanitize_disk_conf(device, new_disk_conf, device->ldev);
1622 
1623 	if (new_disk_conf->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1624 		new_disk_conf->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1625 
1626 	fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1627 	if (fifo_size != device->rs_plan_s->size) {
1628 		new_plan = fifo_alloc(fifo_size);
1629 		if (!new_plan) {
1630 			drbd_err(device, "kmalloc of fifo_buffer failed");
1631 			retcode = ERR_NOMEM;
1632 			goto fail_unlock;
1633 		}
1634 	}
1635 
1636 	err = disk_opts_check_al_size(device, new_disk_conf);
1637 	if (err) {
1638 		/* Could be just "busy". Ignore?
1639 		 * Introduce dedicated error code? */
1640 		drbd_msg_put_info(adm_ctx->reply_skb,
1641 			"Try again without changing current al-extents setting");
1642 		retcode = ERR_NOMEM;
1643 		goto fail_unlock;
1644 	}
1645 
1646 	lock_all_resources();
1647 	retcode = drbd_resync_after_valid(device, new_disk_conf->resync_after);
1648 	if (retcode == NO_ERROR) {
1649 		rcu_assign_pointer(device->ldev->disk_conf, new_disk_conf);
1650 		drbd_resync_after_changed(device);
1651 	}
1652 	unlock_all_resources();
1653 
1654 	if (retcode != NO_ERROR)
1655 		goto fail_unlock;
1656 
1657 	if (new_plan) {
1658 		old_plan = device->rs_plan_s;
1659 		rcu_assign_pointer(device->rs_plan_s, new_plan);
1660 	}
1661 
1662 	mutex_unlock(&device->resource->conf_update);
1663 
1664 	if (new_disk_conf->al_updates)
1665 		device->ldev->md.flags &= ~MDF_AL_DISABLED;
1666 	else
1667 		device->ldev->md.flags |= MDF_AL_DISABLED;
1668 
1669 	if (new_disk_conf->md_flushes)
1670 		clear_bit(MD_NO_FUA, &device->flags);
1671 	else
1672 		set_bit(MD_NO_FUA, &device->flags);
1673 
1674 	if (write_ordering_changed(old_disk_conf, new_disk_conf))
1675 		drbd_bump_write_ordering(device->resource, NULL, WO_BDEV_FLUSH);
1676 
1677 	if (old_disk_conf->discard_zeroes_if_aligned !=
1678 	    new_disk_conf->discard_zeroes_if_aligned)
1679 		drbd_reconsider_queue_parameters(device, device->ldev, NULL);
1680 
1681 	drbd_md_sync(device);
1682 
1683 	if (device->state.conn >= C_CONNECTED) {
1684 		struct drbd_peer_device *peer_device;
1685 
1686 		for_each_peer_device(peer_device, device)
1687 			drbd_send_sync_param(peer_device);
1688 	}
1689 
1690 	kvfree_rcu_mightsleep(old_disk_conf);
1691 	kfree(old_plan);
1692 	mod_timer(&device->request_timer, jiffies + HZ);
1693 	goto success;
1694 
1695 fail_unlock:
1696 	mutex_unlock(&device->resource->conf_update);
1697  fail:
1698 	kfree(new_disk_conf);
1699 	kfree(new_plan);
1700 success:
1701 	put_ldev(device);
1702  out:
1703 	mutex_unlock(&adm_ctx->resource->adm_mutex);
1704  finish:
1705 	adm_ctx->reply_dh->ret_code = retcode;
1706 	return 0;
1707 }
1708 
1709 static struct file *open_backing_dev(struct drbd_device *device,
1710 		const char *bdev_path, void *claim_ptr, bool do_bd_link)
1711 {
1712 	struct file *file;
1713 	int err = 0;
1714 
1715 	file = bdev_file_open_by_path(bdev_path, BLK_OPEN_READ | BLK_OPEN_WRITE,
1716 				      claim_ptr, NULL);
1717 	if (IS_ERR(file)) {
1718 		drbd_err(device, "open(\"%s\") failed with %ld\n",
1719 				bdev_path, PTR_ERR(file));
1720 		return file;
1721 	}
1722 
1723 	if (!do_bd_link)
1724 		return file;
1725 
1726 	err = bd_link_disk_holder(file_bdev(file), device->vdisk);
1727 	if (err) {
1728 		fput(file);
1729 		drbd_err(device, "bd_link_disk_holder(\"%s\", ...) failed with %d\n",
1730 				bdev_path, err);
1731 		file = ERR_PTR(err);
1732 	}
1733 	return file;
1734 }
1735 
1736 static int open_backing_devices(struct drbd_device *device,
1737 		struct disk_conf *new_disk_conf,
1738 		struct drbd_backing_dev *nbc)
1739 {
1740 	struct file *file;
1741 
1742 	file = open_backing_dev(device, new_disk_conf->backing_dev, device,
1743 				  true);
1744 	if (IS_ERR(file))
1745 		return ERR_OPEN_DISK;
1746 	nbc->backing_bdev = file_bdev(file);
1747 	nbc->backing_bdev_file = file;
1748 
1749 	/*
1750 	 * meta_dev_idx >= 0: external fixed size, possibly multiple
1751 	 * drbd sharing one meta device.  TODO in that case, paranoia
1752 	 * check that [md_bdev, meta_dev_idx] is not yet used by some
1753 	 * other drbd minor!  (if you use drbd.conf + drbdadm, that
1754 	 * should check it for you already; but if you don't, or
1755 	 * someone fooled it, we need to double check here)
1756 	 */
1757 	file = open_backing_dev(device, new_disk_conf->meta_dev,
1758 		/* claim ptr: device, if claimed exclusively; shared drbd_m_holder,
1759 		 * if potentially shared with other drbd minors */
1760 			(new_disk_conf->meta_dev_idx < 0) ? (void*)device : (void*)drbd_m_holder,
1761 		/* avoid double bd_claim_by_disk() for the same (source,target) tuple,
1762 		 * as would happen with internal metadata. */
1763 			(new_disk_conf->meta_dev_idx != DRBD_MD_INDEX_FLEX_INT &&
1764 			 new_disk_conf->meta_dev_idx != DRBD_MD_INDEX_INTERNAL));
1765 	if (IS_ERR(file))
1766 		return ERR_OPEN_MD_DISK;
1767 	nbc->md_bdev = file_bdev(file);
1768 	nbc->f_md_bdev = file;
1769 	return NO_ERROR;
1770 }
1771 
1772 static void close_backing_dev(struct drbd_device *device,
1773 		struct file *bdev_file, bool do_bd_unlink)
1774 {
1775 	if (!bdev_file)
1776 		return;
1777 	if (do_bd_unlink)
1778 		bd_unlink_disk_holder(file_bdev(bdev_file), device->vdisk);
1779 	fput(bdev_file);
1780 }
1781 
1782 void drbd_backing_dev_free(struct drbd_device *device, struct drbd_backing_dev *ldev)
1783 {
1784 	if (ldev == NULL)
1785 		return;
1786 
1787 	close_backing_dev(device, ldev->f_md_bdev,
1788 			  ldev->md_bdev != ldev->backing_bdev);
1789 	close_backing_dev(device, ldev->backing_bdev_file, true);
1790 
1791 	kfree(ldev->disk_conf);
1792 	kfree(ldev);
1793 }
1794 
1795 int drbd_nl_attach_doit(struct sk_buff *skb, struct genl_info *info)
1796 {
1797 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
1798 	struct drbd_device *device;
1799 	struct drbd_peer_device *peer_device;
1800 	struct drbd_connection *connection;
1801 	int err;
1802 	enum drbd_ret_code retcode;
1803 	enum determine_dev_size dd;
1804 	sector_t max_possible_sectors;
1805 	sector_t min_md_device_sectors;
1806 	struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1807 	struct disk_conf *new_disk_conf = NULL;
1808 	struct lru_cache *resync_lru = NULL;
1809 	struct fifo_buffer *new_plan = NULL;
1810 	union drbd_state ns, os;
1811 	enum drbd_state_rv rv;
1812 	struct net_conf *nc;
1813 
1814 	if (!adm_ctx->reply_skb)
1815 		return 0;
1816 	retcode = adm_ctx->reply_dh->ret_code;
1817 	if (retcode != NO_ERROR)
1818 		goto finish;
1819 
1820 	device = adm_ctx->device;
1821 	mutex_lock(&adm_ctx->resource->adm_mutex);
1822 	peer_device = first_peer_device(device);
1823 	connection = peer_device->connection;
1824 	conn_reconfig_start(connection);
1825 
1826 	/* if you want to reconfigure, please tear down first */
1827 	if (device->state.disk > D_DISKLESS) {
1828 		retcode = ERR_DISK_CONFIGURED;
1829 		goto fail;
1830 	}
1831 	/* It may just now have detached because of IO error.  Make sure
1832 	 * drbd_ldev_destroy is done already, we may end up here very fast,
1833 	 * e.g. if someone calls attach from the on-io-error handler,
1834 	 * to realize a "hot spare" feature (not that I'd recommend that) */
1835 	wait_event(device->misc_wait, !test_bit(GOING_DISKLESS, &device->flags));
1836 
1837 	/* make sure there is no leftover from previous force-detach attempts */
1838 	clear_bit(FORCE_DETACH, &device->flags);
1839 	clear_bit(WAS_IO_ERROR, &device->flags);
1840 	clear_bit(WAS_READ_ERROR, &device->flags);
1841 
1842 	/* and no leftover from previously aborted resync or verify, either */
1843 	device->rs_total = 0;
1844 	device->rs_failed = 0;
1845 	atomic_set(&device->rs_pending_cnt, 0);
1846 
1847 	/* allocation not in the IO path, drbdsetup context */
1848 	nbc = kzalloc_obj(struct drbd_backing_dev);
1849 	if (!nbc) {
1850 		retcode = ERR_NOMEM;
1851 		goto fail;
1852 	}
1853 	spin_lock_init(&nbc->md.uuid_lock);
1854 
1855 	new_disk_conf = kzalloc_obj(struct disk_conf);
1856 	if (!new_disk_conf) {
1857 		retcode = ERR_NOMEM;
1858 		goto fail;
1859 	}
1860 	nbc->disk_conf = new_disk_conf;
1861 
1862 	set_disk_conf_defaults(new_disk_conf);
1863 	err = disk_conf_from_attrs(new_disk_conf, info);
1864 	if (err) {
1865 		retcode = ERR_MANDATORY_TAG;
1866 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
1867 		goto fail;
1868 	}
1869 
1870 	if (new_disk_conf->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1871 		new_disk_conf->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1872 
1873 	new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1874 	if (!new_plan) {
1875 		retcode = ERR_NOMEM;
1876 		goto fail;
1877 	}
1878 
1879 	if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1880 		retcode = ERR_MD_IDX_INVALID;
1881 		goto fail;
1882 	}
1883 
1884 	rcu_read_lock();
1885 	nc = rcu_dereference(connection->net_conf);
1886 	if (nc) {
1887 		if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1888 			rcu_read_unlock();
1889 			retcode = ERR_STONITH_AND_PROT_A;
1890 			goto fail;
1891 		}
1892 	}
1893 	rcu_read_unlock();
1894 
1895 	retcode = open_backing_devices(device, new_disk_conf, nbc);
1896 	if (retcode != NO_ERROR)
1897 		goto fail;
1898 
1899 	if ((nbc->backing_bdev == nbc->md_bdev) !=
1900 	    (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1901 	     new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1902 		retcode = ERR_MD_IDX_INVALID;
1903 		goto fail;
1904 	}
1905 
1906 	resync_lru = lc_create("resync", drbd_bm_ext_cache,
1907 			1, 61, sizeof(struct bm_extent),
1908 			offsetof(struct bm_extent, lce));
1909 	if (!resync_lru) {
1910 		retcode = ERR_NOMEM;
1911 		goto fail;
1912 	}
1913 
1914 	/* Read our meta data super block early.
1915 	 * This also sets other on-disk offsets. */
1916 	retcode = drbd_md_read(device, nbc);
1917 	if (retcode != NO_ERROR)
1918 		goto fail;
1919 
1920 	sanitize_disk_conf(device, new_disk_conf, nbc);
1921 
1922 	if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1923 		drbd_err(device, "max capacity %llu smaller than disk size %llu\n",
1924 			(unsigned long long) drbd_get_max_capacity(nbc),
1925 			(unsigned long long) new_disk_conf->disk_size);
1926 		retcode = ERR_DISK_TOO_SMALL;
1927 		goto fail;
1928 	}
1929 
1930 	if (new_disk_conf->meta_dev_idx < 0) {
1931 		max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1932 		/* at least one MB, otherwise it does not make sense */
1933 		min_md_device_sectors = (2<<10);
1934 	} else {
1935 		max_possible_sectors = DRBD_MAX_SECTORS;
1936 		min_md_device_sectors = MD_128MB_SECT * (new_disk_conf->meta_dev_idx + 1);
1937 	}
1938 
1939 	if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1940 		retcode = ERR_MD_DISK_TOO_SMALL;
1941 		drbd_warn(device, "refusing attach: md-device too small, "
1942 		     "at least %llu sectors needed for this meta-disk type\n",
1943 		     (unsigned long long) min_md_device_sectors);
1944 		goto fail;
1945 	}
1946 
1947 	/* Make sure the new disk is big enough
1948 	 * (we may currently be R_PRIMARY with no local disk...) */
1949 	if (drbd_get_max_capacity(nbc) < get_capacity(device->vdisk)) {
1950 		retcode = ERR_DISK_TOO_SMALL;
1951 		goto fail;
1952 	}
1953 
1954 	nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1955 
1956 	if (nbc->known_size > max_possible_sectors) {
1957 		drbd_warn(device, "==> truncating very big lower level device "
1958 			"to currently maximum possible %llu sectors <==\n",
1959 			(unsigned long long) max_possible_sectors);
1960 		if (new_disk_conf->meta_dev_idx >= 0)
1961 			drbd_warn(device, "==>> using internal or flexible "
1962 				      "meta data may help <<==\n");
1963 	}
1964 
1965 	drbd_suspend_io(device);
1966 	/* also wait for the last barrier ack. */
1967 	/* FIXME see also https://daiquiri.linbit/cgi-bin/bugzilla/show_bug.cgi?id=171
1968 	 * We need a way to either ignore barrier acks for barriers sent before a device
1969 	 * was attached, or a way to wait for all pending barrier acks to come in.
1970 	 * As barriers are counted per resource,
1971 	 * we'd need to suspend io on all devices of a resource.
1972 	 */
1973 	wait_event(device->misc_wait, !atomic_read(&device->ap_pending_cnt) || drbd_suspended(device));
1974 	/* and for any other previously queued work */
1975 	drbd_flush_workqueue(&connection->sender_work);
1976 
1977 	rv = _drbd_request_state(device, NS(disk, D_ATTACHING), CS_VERBOSE);
1978 	retcode = (enum drbd_ret_code)rv;
1979 	drbd_resume_io(device);
1980 	if (rv < SS_SUCCESS)
1981 		goto fail;
1982 
1983 	if (!get_ldev_if_state(device, D_ATTACHING))
1984 		goto force_diskless;
1985 
1986 	if (!device->bitmap) {
1987 		if (drbd_bm_init(device)) {
1988 			retcode = ERR_NOMEM;
1989 			goto force_diskless_dec;
1990 		}
1991 	}
1992 
1993 	if (device->state.pdsk != D_UP_TO_DATE && device->ed_uuid &&
1994 	    (device->state.role == R_PRIMARY || device->state.peer == R_PRIMARY) &&
1995             (device->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1996 		drbd_err(device, "Can only attach to data with current UUID=%016llX\n",
1997 		    (unsigned long long)device->ed_uuid);
1998 		retcode = ERR_DATA_NOT_CURRENT;
1999 		goto force_diskless_dec;
2000 	}
2001 
2002 	/* Since we are diskless, fix the activity log first... */
2003 	if (drbd_check_al_size(device, new_disk_conf)) {
2004 		retcode = ERR_NOMEM;
2005 		goto force_diskless_dec;
2006 	}
2007 
2008 	/* Prevent shrinking of consistent devices ! */
2009 	{
2010 	unsigned long long nsz = drbd_new_dev_size(device, nbc, nbc->disk_conf->disk_size, 0);
2011 	unsigned long long eff = nbc->md.la_size_sect;
2012 	if (drbd_md_test_flag(nbc, MDF_CONSISTENT) && nsz < eff) {
2013 		if (nsz == nbc->disk_conf->disk_size) {
2014 			drbd_warn(device, "truncating a consistent device during attach (%llu < %llu)\n", nsz, eff);
2015 		} else {
2016 			drbd_warn(device, "refusing to truncate a consistent device (%llu < %llu)\n", nsz, eff);
2017 			drbd_msg_sprintf_info(adm_ctx->reply_skb,
2018 				"To-be-attached device has last effective > current size, and is consistent\n"
2019 				"(%llu > %llu sectors). Refusing to attach.", eff, nsz);
2020 			retcode = ERR_IMPLICIT_SHRINK;
2021 			goto force_diskless_dec;
2022 		}
2023 	}
2024 	}
2025 
2026 	lock_all_resources();
2027 	retcode = drbd_resync_after_valid(device, new_disk_conf->resync_after);
2028 	if (retcode != NO_ERROR) {
2029 		unlock_all_resources();
2030 		goto force_diskless_dec;
2031 	}
2032 
2033 	/* Reset the "barriers don't work" bits here, then force meta data to
2034 	 * be written, to ensure we determine if barriers are supported. */
2035 	if (new_disk_conf->md_flushes)
2036 		clear_bit(MD_NO_FUA, &device->flags);
2037 	else
2038 		set_bit(MD_NO_FUA, &device->flags);
2039 
2040 	/* Point of no return reached.
2041 	 * Devices and memory are no longer released by error cleanup below.
2042 	 * now device takes over responsibility, and the state engine should
2043 	 * clean it up somewhere.  */
2044 	D_ASSERT(device, device->ldev == NULL);
2045 	device->ldev = nbc;
2046 	device->resync = resync_lru;
2047 	device->rs_plan_s = new_plan;
2048 	nbc = NULL;
2049 	resync_lru = NULL;
2050 	new_disk_conf = NULL;
2051 	new_plan = NULL;
2052 
2053 	drbd_resync_after_changed(device);
2054 	drbd_bump_write_ordering(device->resource, device->ldev, WO_BDEV_FLUSH);
2055 	unlock_all_resources();
2056 
2057 	if (drbd_md_test_flag(device->ldev, MDF_CRASHED_PRIMARY))
2058 		set_bit(CRASHED_PRIMARY, &device->flags);
2059 	else
2060 		clear_bit(CRASHED_PRIMARY, &device->flags);
2061 
2062 	if (drbd_md_test_flag(device->ldev, MDF_PRIMARY_IND) &&
2063 	    !(device->state.role == R_PRIMARY && device->resource->susp_nod))
2064 		set_bit(CRASHED_PRIMARY, &device->flags);
2065 
2066 	device->send_cnt = 0;
2067 	device->recv_cnt = 0;
2068 	device->read_cnt = 0;
2069 	device->writ_cnt = 0;
2070 
2071 	drbd_reconsider_queue_parameters(device, device->ldev, NULL);
2072 
2073 	/* If I am currently not R_PRIMARY,
2074 	 * but meta data primary indicator is set,
2075 	 * I just now recover from a hard crash,
2076 	 * and have been R_PRIMARY before that crash.
2077 	 *
2078 	 * Now, if I had no connection before that crash
2079 	 * (have been degraded R_PRIMARY), chances are that
2080 	 * I won't find my peer now either.
2081 	 *
2082 	 * In that case, and _only_ in that case,
2083 	 * we use the degr-wfc-timeout instead of the default,
2084 	 * so we can automatically recover from a crash of a
2085 	 * degraded but active "cluster" after a certain timeout.
2086 	 */
2087 	clear_bit(USE_DEGR_WFC_T, &device->flags);
2088 	if (device->state.role != R_PRIMARY &&
2089 	     drbd_md_test_flag(device->ldev, MDF_PRIMARY_IND) &&
2090 	    !drbd_md_test_flag(device->ldev, MDF_CONNECTED_IND))
2091 		set_bit(USE_DEGR_WFC_T, &device->flags);
2092 
2093 	dd = drbd_determine_dev_size(device, 0, NULL);
2094 	if (dd <= DS_ERROR) {
2095 		retcode = ERR_NOMEM_BITMAP;
2096 		goto force_diskless_dec;
2097 	} else if (dd == DS_GREW)
2098 		set_bit(RESYNC_AFTER_NEG, &device->flags);
2099 
2100 	if (drbd_md_test_flag(device->ldev, MDF_FULL_SYNC) ||
2101 	    (test_bit(CRASHED_PRIMARY, &device->flags) &&
2102 	     drbd_md_test_flag(device->ldev, MDF_AL_DISABLED))) {
2103 		drbd_info(device, "Assuming that all blocks are out of sync "
2104 		     "(aka FullSync)\n");
2105 		if (drbd_bitmap_io(device, &drbd_bmio_set_n_write,
2106 			"set_n_write from attaching", BM_LOCKED_MASK,
2107 			NULL)) {
2108 			retcode = ERR_IO_MD_DISK;
2109 			goto force_diskless_dec;
2110 		}
2111 	} else {
2112 		if (drbd_bitmap_io(device, &drbd_bm_read,
2113 			"read from attaching", BM_LOCKED_MASK,
2114 			NULL)) {
2115 			retcode = ERR_IO_MD_DISK;
2116 			goto force_diskless_dec;
2117 		}
2118 	}
2119 
2120 	if (_drbd_bm_total_weight(device) == drbd_bm_bits(device))
2121 		drbd_suspend_al(device); /* IO is still suspended here... */
2122 
2123 	spin_lock_irq(&device->resource->req_lock);
2124 	os = drbd_read_state(device);
2125 	ns = os;
2126 	/* If MDF_CONSISTENT is not set go into inconsistent state,
2127 	   otherwise investigate MDF_WasUpToDate...
2128 	   If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
2129 	   otherwise into D_CONSISTENT state.
2130 	*/
2131 	if (drbd_md_test_flag(device->ldev, MDF_CONSISTENT)) {
2132 		if (drbd_md_test_flag(device->ldev, MDF_WAS_UP_TO_DATE))
2133 			ns.disk = D_CONSISTENT;
2134 		else
2135 			ns.disk = D_OUTDATED;
2136 	} else {
2137 		ns.disk = D_INCONSISTENT;
2138 	}
2139 
2140 	if (drbd_md_test_flag(device->ldev, MDF_PEER_OUT_DATED))
2141 		ns.pdsk = D_OUTDATED;
2142 
2143 	rcu_read_lock();
2144 	if (ns.disk == D_CONSISTENT &&
2145 	    (ns.pdsk == D_OUTDATED || rcu_dereference(device->ldev->disk_conf)->fencing == FP_DONT_CARE))
2146 		ns.disk = D_UP_TO_DATE;
2147 
2148 	/* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
2149 	   MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
2150 	   this point, because drbd_request_state() modifies these
2151 	   flags. */
2152 
2153 	if (rcu_dereference(device->ldev->disk_conf)->al_updates)
2154 		device->ldev->md.flags &= ~MDF_AL_DISABLED;
2155 	else
2156 		device->ldev->md.flags |= MDF_AL_DISABLED;
2157 
2158 	rcu_read_unlock();
2159 
2160 	/* In case we are C_CONNECTED postpone any decision on the new disk
2161 	   state after the negotiation phase. */
2162 	if (device->state.conn == C_CONNECTED) {
2163 		device->new_state_tmp.i = ns.i;
2164 		ns.i = os.i;
2165 		ns.disk = D_NEGOTIATING;
2166 
2167 		/* We expect to receive up-to-date UUIDs soon.
2168 		   To avoid a race in receive_state, free p_uuid while
2169 		   holding req_lock. I.e. atomic with the state change */
2170 		kfree(device->p_uuid);
2171 		device->p_uuid = NULL;
2172 	}
2173 
2174 	rv = _drbd_set_state(device, ns, CS_VERBOSE, NULL);
2175 	spin_unlock_irq(&device->resource->req_lock);
2176 
2177 	if (rv < SS_SUCCESS)
2178 		goto force_diskless_dec;
2179 
2180 	mod_timer(&device->request_timer, jiffies + HZ);
2181 
2182 	if (device->state.role == R_PRIMARY)
2183 		device->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
2184 	else
2185 		device->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
2186 
2187 	drbd_md_mark_dirty(device);
2188 	drbd_md_sync(device);
2189 
2190 	kobject_uevent(&disk_to_dev(device->vdisk)->kobj, KOBJ_CHANGE);
2191 	put_ldev(device);
2192 	conn_reconfig_done(connection);
2193 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2194 	adm_ctx->reply_dh->ret_code = retcode;
2195 	return 0;
2196 
2197  force_diskless_dec:
2198 	put_ldev(device);
2199  force_diskless:
2200 	drbd_force_state(device, NS(disk, D_DISKLESS));
2201 	drbd_md_sync(device);
2202  fail:
2203 	conn_reconfig_done(connection);
2204 	if (nbc) {
2205 		close_backing_dev(device, nbc->f_md_bdev,
2206 			  nbc->md_bdev != nbc->backing_bdev);
2207 		close_backing_dev(device, nbc->backing_bdev_file, true);
2208 		kfree(nbc);
2209 	}
2210 	kfree(new_disk_conf);
2211 	lc_destroy(resync_lru);
2212 	kfree(new_plan);
2213 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2214  finish:
2215 	adm_ctx->reply_dh->ret_code = retcode;
2216 	return 0;
2217 }
2218 
2219 static int adm_detach(struct drbd_device *device, int force)
2220 {
2221 	if (force) {
2222 		set_bit(FORCE_DETACH, &device->flags);
2223 		drbd_force_state(device, NS(disk, D_FAILED));
2224 		return SS_SUCCESS;
2225 	}
2226 
2227 	return drbd_request_detach_interruptible(device);
2228 }
2229 
2230 /* Detaching the disk is a process in multiple stages.  First we need to lock
2231  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
2232  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
2233  * internal references as well.
2234  * Only then we have finally detached. */
2235 int drbd_nl_detach_doit(struct sk_buff *skb, struct genl_info *info)
2236 {
2237 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2238 	enum drbd_ret_code retcode;
2239 	struct detach_parms parms = { };
2240 	int err;
2241 
2242 	if (!adm_ctx->reply_skb)
2243 		return 0;
2244 	retcode = adm_ctx->reply_dh->ret_code;
2245 	if (retcode != NO_ERROR)
2246 		goto out;
2247 
2248 	if (info->attrs[DRBD_NLA_DETACH_PARMS]) {
2249 		err = detach_parms_from_attrs(&parms, info);
2250 		if (err) {
2251 			retcode = ERR_MANDATORY_TAG;
2252 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
2253 			goto out;
2254 		}
2255 	}
2256 
2257 	mutex_lock(&adm_ctx->resource->adm_mutex);
2258 	retcode = adm_detach(adm_ctx->device, parms.force_detach);
2259 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2260 out:
2261 	adm_ctx->reply_dh->ret_code = retcode;
2262 	return 0;
2263 }
2264 
2265 static bool conn_resync_running(struct drbd_connection *connection)
2266 {
2267 	struct drbd_peer_device *peer_device;
2268 	bool rv = false;
2269 	int vnr;
2270 
2271 	rcu_read_lock();
2272 	idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
2273 		struct drbd_device *device = peer_device->device;
2274 		if (device->state.conn == C_SYNC_SOURCE ||
2275 		    device->state.conn == C_SYNC_TARGET ||
2276 		    device->state.conn == C_PAUSED_SYNC_S ||
2277 		    device->state.conn == C_PAUSED_SYNC_T) {
2278 			rv = true;
2279 			break;
2280 		}
2281 	}
2282 	rcu_read_unlock();
2283 
2284 	return rv;
2285 }
2286 
2287 static bool conn_ov_running(struct drbd_connection *connection)
2288 {
2289 	struct drbd_peer_device *peer_device;
2290 	bool rv = false;
2291 	int vnr;
2292 
2293 	rcu_read_lock();
2294 	idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
2295 		struct drbd_device *device = peer_device->device;
2296 		if (device->state.conn == C_VERIFY_S ||
2297 		    device->state.conn == C_VERIFY_T) {
2298 			rv = true;
2299 			break;
2300 		}
2301 	}
2302 	rcu_read_unlock();
2303 
2304 	return rv;
2305 }
2306 
2307 static enum drbd_ret_code
2308 _check_net_options(struct drbd_connection *connection, struct net_conf *old_net_conf, struct net_conf *new_net_conf)
2309 {
2310 	struct drbd_peer_device *peer_device;
2311 	int i;
2312 
2313 	if (old_net_conf && connection->cstate == C_WF_REPORT_PARAMS && connection->agreed_pro_version < 100) {
2314 		if (new_net_conf->wire_protocol != old_net_conf->wire_protocol)
2315 			return ERR_NEED_APV_100;
2316 
2317 		if (new_net_conf->two_primaries != old_net_conf->two_primaries)
2318 			return ERR_NEED_APV_100;
2319 
2320 		if (strcmp(new_net_conf->integrity_alg, old_net_conf->integrity_alg))
2321 			return ERR_NEED_APV_100;
2322 	}
2323 
2324 	if (!new_net_conf->two_primaries &&
2325 	    conn_highest_role(connection) == R_PRIMARY &&
2326 	    conn_highest_peer(connection) == R_PRIMARY)
2327 		return ERR_NEED_ALLOW_TWO_PRI;
2328 
2329 	if (new_net_conf->two_primaries &&
2330 	    (new_net_conf->wire_protocol != DRBD_PROT_C))
2331 		return ERR_NOT_PROTO_C;
2332 
2333 	idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2334 		struct drbd_device *device = peer_device->device;
2335 		if (get_ldev(device)) {
2336 			enum drbd_fencing_p fp = rcu_dereference(device->ldev->disk_conf)->fencing;
2337 			put_ldev(device);
2338 			if (new_net_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
2339 				return ERR_STONITH_AND_PROT_A;
2340 		}
2341 		if (device->state.role == R_PRIMARY && new_net_conf->discard_my_data)
2342 			return ERR_DISCARD_IMPOSSIBLE;
2343 	}
2344 
2345 	if (new_net_conf->on_congestion != OC_BLOCK && new_net_conf->wire_protocol != DRBD_PROT_A)
2346 		return ERR_CONG_NOT_PROTO_A;
2347 
2348 	return NO_ERROR;
2349 }
2350 
2351 static enum drbd_ret_code
2352 check_net_options(struct drbd_connection *connection, struct net_conf *new_net_conf)
2353 {
2354 	enum drbd_ret_code rv;
2355 	struct drbd_peer_device *peer_device;
2356 	int i;
2357 
2358 	rcu_read_lock();
2359 	rv = _check_net_options(connection, rcu_dereference(connection->net_conf), new_net_conf);
2360 	rcu_read_unlock();
2361 
2362 	/* connection->peer_devices protected by genl_lock() here */
2363 	idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2364 		struct drbd_device *device = peer_device->device;
2365 		if (!device->bitmap) {
2366 			if (drbd_bm_init(device))
2367 				return ERR_NOMEM;
2368 		}
2369 	}
2370 
2371 	return rv;
2372 }
2373 
2374 struct crypto {
2375 	struct crypto_shash *verify_tfm;
2376 	struct crypto_shash *csums_tfm;
2377 	struct crypto_shash *cram_hmac_tfm;
2378 	struct crypto_shash *integrity_tfm;
2379 };
2380 
2381 static int
2382 alloc_shash(struct crypto_shash **tfm, char *tfm_name, int err_alg)
2383 {
2384 	if (!tfm_name[0])
2385 		return NO_ERROR;
2386 
2387 	*tfm = crypto_alloc_shash(tfm_name, 0, 0);
2388 	if (IS_ERR(*tfm)) {
2389 		*tfm = NULL;
2390 		return err_alg;
2391 	}
2392 
2393 	return NO_ERROR;
2394 }
2395 
2396 static enum drbd_ret_code
2397 alloc_crypto(struct crypto *crypto, struct net_conf *new_net_conf)
2398 {
2399 	char hmac_name[CRYPTO_MAX_ALG_NAME];
2400 	enum drbd_ret_code rv;
2401 
2402 	rv = alloc_shash(&crypto->csums_tfm, new_net_conf->csums_alg,
2403 			 ERR_CSUMS_ALG);
2404 	if (rv != NO_ERROR)
2405 		return rv;
2406 	rv = alloc_shash(&crypto->verify_tfm, new_net_conf->verify_alg,
2407 			 ERR_VERIFY_ALG);
2408 	if (rv != NO_ERROR)
2409 		return rv;
2410 	rv = alloc_shash(&crypto->integrity_tfm, new_net_conf->integrity_alg,
2411 			 ERR_INTEGRITY_ALG);
2412 	if (rv != NO_ERROR)
2413 		return rv;
2414 	if (new_net_conf->cram_hmac_alg[0] != 0) {
2415 		snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
2416 			 new_net_conf->cram_hmac_alg);
2417 
2418 		rv = alloc_shash(&crypto->cram_hmac_tfm, hmac_name,
2419 				 ERR_AUTH_ALG);
2420 	}
2421 
2422 	return rv;
2423 }
2424 
2425 static void free_crypto(struct crypto *crypto)
2426 {
2427 	crypto_free_shash(crypto->cram_hmac_tfm);
2428 	crypto_free_shash(crypto->integrity_tfm);
2429 	crypto_free_shash(crypto->csums_tfm);
2430 	crypto_free_shash(crypto->verify_tfm);
2431 }
2432 
2433 int drbd_nl_chg_net_opts_doit(struct sk_buff *skb, struct genl_info *info)
2434 {
2435 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2436 	enum drbd_ret_code retcode;
2437 	struct drbd_connection *connection;
2438 	struct net_conf *old_net_conf, *new_net_conf = NULL;
2439 	struct nlattr **ntb;
2440 	int err;
2441 	int ovr; /* online verify running */
2442 	int rsr; /* re-sync running */
2443 	struct crypto crypto = { };
2444 
2445 	if (!adm_ctx->reply_skb)
2446 		return 0;
2447 	retcode = adm_ctx->reply_dh->ret_code;
2448 	if (retcode != NO_ERROR)
2449 		goto finish;
2450 
2451 	connection = adm_ctx->connection;
2452 	mutex_lock(&adm_ctx->resource->adm_mutex);
2453 
2454 	new_net_conf = kzalloc_obj(struct net_conf);
2455 	if (!new_net_conf) {
2456 		retcode = ERR_NOMEM;
2457 		goto out;
2458 	}
2459 
2460 	conn_reconfig_start(connection);
2461 
2462 	mutex_lock(&connection->data.mutex);
2463 	mutex_lock(&connection->resource->conf_update);
2464 	old_net_conf = connection->net_conf;
2465 
2466 	if (!old_net_conf) {
2467 		drbd_msg_put_info(adm_ctx->reply_skb, "net conf missing, try connect");
2468 		retcode = ERR_INVALID_REQUEST;
2469 		goto fail;
2470 	}
2471 
2472 	*new_net_conf = *old_net_conf;
2473 	if (should_set_defaults(info))
2474 		set_net_conf_defaults(new_net_conf);
2475 
2476 	err = net_conf_from_attrs(new_net_conf, info);
2477 	if (err && err != -ENOMSG) {
2478 		retcode = ERR_MANDATORY_TAG;
2479 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
2480 		goto fail;
2481 	}
2482 
2483 	err = net_conf_ntb_from_attrs(&ntb, info);
2484 	if (!err) {
2485 		if (has_invariant(ntb, DRBD_A_NET_CONF_DISCARD_MY_DATA) ||
2486 		    has_invariant(ntb, DRBD_A_NET_CONF_TENTATIVE)) {
2487 			retcode = ERR_MANDATORY_TAG;
2488 			drbd_msg_put_info(adm_ctx->reply_skb,
2489 				"cannot change invariant setting");
2490 			kfree(ntb);
2491 			goto fail;
2492 		}
2493 		kfree(ntb);
2494 	}
2495 
2496 	retcode = check_net_options(connection, new_net_conf);
2497 	if (retcode != NO_ERROR)
2498 		goto fail;
2499 
2500 	/* re-sync running */
2501 	rsr = conn_resync_running(connection);
2502 	if (rsr && strcmp(new_net_conf->csums_alg, old_net_conf->csums_alg)) {
2503 		retcode = ERR_CSUMS_RESYNC_RUNNING;
2504 		goto fail;
2505 	}
2506 
2507 	/* online verify running */
2508 	ovr = conn_ov_running(connection);
2509 	if (ovr && strcmp(new_net_conf->verify_alg, old_net_conf->verify_alg)) {
2510 		retcode = ERR_VERIFY_RUNNING;
2511 		goto fail;
2512 	}
2513 
2514 	retcode = alloc_crypto(&crypto, new_net_conf);
2515 	if (retcode != NO_ERROR)
2516 		goto fail;
2517 
2518 	rcu_assign_pointer(connection->net_conf, new_net_conf);
2519 
2520 	if (!rsr) {
2521 		crypto_free_shash(connection->csums_tfm);
2522 		connection->csums_tfm = crypto.csums_tfm;
2523 		crypto.csums_tfm = NULL;
2524 	}
2525 	if (!ovr) {
2526 		crypto_free_shash(connection->verify_tfm);
2527 		connection->verify_tfm = crypto.verify_tfm;
2528 		crypto.verify_tfm = NULL;
2529 	}
2530 
2531 	crypto_free_shash(connection->integrity_tfm);
2532 	connection->integrity_tfm = crypto.integrity_tfm;
2533 	if (connection->cstate >= C_WF_REPORT_PARAMS && connection->agreed_pro_version >= 100)
2534 		/* Do this without trying to take connection->data.mutex again.  */
2535 		__drbd_send_protocol(connection, P_PROTOCOL_UPDATE);
2536 
2537 	crypto_free_shash(connection->cram_hmac_tfm);
2538 	connection->cram_hmac_tfm = crypto.cram_hmac_tfm;
2539 
2540 	mutex_unlock(&connection->resource->conf_update);
2541 	mutex_unlock(&connection->data.mutex);
2542 	kvfree_rcu_mightsleep(old_net_conf);
2543 
2544 	if (connection->cstate >= C_WF_REPORT_PARAMS) {
2545 		struct drbd_peer_device *peer_device;
2546 		int vnr;
2547 
2548 		idr_for_each_entry(&connection->peer_devices, peer_device, vnr)
2549 			drbd_send_sync_param(peer_device);
2550 	}
2551 
2552 	goto done;
2553 
2554  fail:
2555 	mutex_unlock(&connection->resource->conf_update);
2556 	mutex_unlock(&connection->data.mutex);
2557 	free_crypto(&crypto);
2558 	kfree(new_net_conf);
2559  done:
2560 	conn_reconfig_done(connection);
2561  out:
2562 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2563  finish:
2564 	adm_ctx->reply_dh->ret_code = retcode;
2565 	return 0;
2566 }
2567 
2568 static void connection_to_info(struct connection_info *info,
2569 			       struct drbd_connection *connection)
2570 {
2571 	info->conn_connection_state = connection->cstate;
2572 	info->conn_role = conn_highest_peer(connection);
2573 }
2574 
2575 static void peer_device_to_info(struct peer_device_info *info,
2576 				struct drbd_peer_device *peer_device)
2577 {
2578 	struct drbd_device *device = peer_device->device;
2579 
2580 	info->peer_repl_state =
2581 		max_t(enum drbd_conns, C_WF_REPORT_PARAMS, device->state.conn);
2582 	info->peer_disk_state = device->state.pdsk;
2583 	info->peer_resync_susp_user = device->state.user_isp;
2584 	info->peer_resync_susp_peer = device->state.peer_isp;
2585 	info->peer_resync_susp_dependency = device->state.aftr_isp;
2586 }
2587 
2588 int drbd_nl_connect_doit(struct sk_buff *skb, struct genl_info *info)
2589 {
2590 	struct connection_info connection_info;
2591 	enum drbd_notification_type flags;
2592 	unsigned int peer_devices = 0;
2593 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2594 	struct drbd_peer_device *peer_device;
2595 	struct net_conf *old_net_conf, *new_net_conf = NULL;
2596 	struct crypto crypto = { };
2597 	struct drbd_resource *resource;
2598 	struct drbd_connection *connection;
2599 	enum drbd_ret_code retcode;
2600 	enum drbd_state_rv rv;
2601 	int i;
2602 	int err;
2603 
2604 	if (!adm_ctx->reply_skb)
2605 		return 0;
2606 	retcode = adm_ctx->reply_dh->ret_code;
2607 	if (retcode != NO_ERROR)
2608 		goto out;
2609 	if (!(adm_ctx->my_addr && adm_ctx->peer_addr)) {
2610 		drbd_msg_put_info(adm_ctx->reply_skb, "connection endpoint(s) missing");
2611 		retcode = ERR_INVALID_REQUEST;
2612 		goto out;
2613 	}
2614 
2615 	/* No need for _rcu here. All reconfiguration is
2616 	 * strictly serialized on genl_lock(). We are protected against
2617 	 * concurrent reconfiguration/addition/deletion */
2618 	for_each_resource(resource, &drbd_resources) {
2619 		for_each_connection(connection, resource) {
2620 			if (nla_len(adm_ctx->my_addr) == connection->my_addr_len &&
2621 			    !memcmp(nla_data(adm_ctx->my_addr), &connection->my_addr,
2622 				    connection->my_addr_len)) {
2623 				retcode = ERR_LOCAL_ADDR;
2624 				goto out;
2625 			}
2626 
2627 			if (nla_len(adm_ctx->peer_addr) == connection->peer_addr_len &&
2628 			    !memcmp(nla_data(adm_ctx->peer_addr), &connection->peer_addr,
2629 				    connection->peer_addr_len)) {
2630 				retcode = ERR_PEER_ADDR;
2631 				goto out;
2632 			}
2633 		}
2634 	}
2635 
2636 	mutex_lock(&adm_ctx->resource->adm_mutex);
2637 	connection = first_connection(adm_ctx->resource);
2638 	conn_reconfig_start(connection);
2639 
2640 	if (connection->cstate > C_STANDALONE) {
2641 		retcode = ERR_NET_CONFIGURED;
2642 		goto fail;
2643 	}
2644 
2645 	/* allocation not in the IO path, drbdsetup / netlink process context */
2646 	new_net_conf = kzalloc_obj(*new_net_conf);
2647 	if (!new_net_conf) {
2648 		retcode = ERR_NOMEM;
2649 		goto fail;
2650 	}
2651 
2652 	set_net_conf_defaults(new_net_conf);
2653 
2654 	err = net_conf_from_attrs(new_net_conf, info);
2655 	if (err && err != -ENOMSG) {
2656 		retcode = ERR_MANDATORY_TAG;
2657 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
2658 		goto fail;
2659 	}
2660 
2661 	retcode = check_net_options(connection, new_net_conf);
2662 	if (retcode != NO_ERROR)
2663 		goto fail;
2664 
2665 	retcode = alloc_crypto(&crypto, new_net_conf);
2666 	if (retcode != NO_ERROR)
2667 		goto fail;
2668 
2669 	((char *)new_net_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2670 
2671 	drbd_flush_workqueue(&connection->sender_work);
2672 
2673 	mutex_lock(&adm_ctx->resource->conf_update);
2674 	old_net_conf = connection->net_conf;
2675 	if (old_net_conf) {
2676 		retcode = ERR_NET_CONFIGURED;
2677 		mutex_unlock(&adm_ctx->resource->conf_update);
2678 		goto fail;
2679 	}
2680 	rcu_assign_pointer(connection->net_conf, new_net_conf);
2681 
2682 	conn_free_crypto(connection);
2683 	connection->cram_hmac_tfm = crypto.cram_hmac_tfm;
2684 	connection->integrity_tfm = crypto.integrity_tfm;
2685 	connection->csums_tfm = crypto.csums_tfm;
2686 	connection->verify_tfm = crypto.verify_tfm;
2687 
2688 	connection->my_addr_len = nla_len(adm_ctx->my_addr);
2689 	memcpy(&connection->my_addr, nla_data(adm_ctx->my_addr), connection->my_addr_len);
2690 	connection->peer_addr_len = nla_len(adm_ctx->peer_addr);
2691 	memcpy(&connection->peer_addr, nla_data(adm_ctx->peer_addr), connection->peer_addr_len);
2692 
2693 	idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2694 		peer_devices++;
2695 	}
2696 
2697 	connection_to_info(&connection_info, connection);
2698 	flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
2699 	mutex_lock(&notification_mutex);
2700 	notify_connection_state(NULL, 0, connection, &connection_info, NOTIFY_CREATE | flags);
2701 	idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2702 		struct peer_device_info peer_device_info;
2703 
2704 		peer_device_to_info(&peer_device_info, peer_device);
2705 		flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
2706 		notify_peer_device_state(NULL, 0, peer_device, &peer_device_info, NOTIFY_CREATE | flags);
2707 	}
2708 	mutex_unlock(&notification_mutex);
2709 	mutex_unlock(&adm_ctx->resource->conf_update);
2710 
2711 	rcu_read_lock();
2712 	idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2713 		struct drbd_device *device = peer_device->device;
2714 		device->send_cnt = 0;
2715 		device->recv_cnt = 0;
2716 	}
2717 	rcu_read_unlock();
2718 
2719 	rv = conn_request_state(connection, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2720 
2721 	conn_reconfig_done(connection);
2722 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2723 	adm_ctx->reply_dh->ret_code = rv;
2724 	return 0;
2725 
2726 fail:
2727 	free_crypto(&crypto);
2728 	kfree(new_net_conf);
2729 
2730 	conn_reconfig_done(connection);
2731 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2732 out:
2733 	adm_ctx->reply_dh->ret_code = retcode;
2734 	return 0;
2735 }
2736 
2737 static enum drbd_state_rv conn_try_disconnect(struct drbd_connection *connection, bool force)
2738 {
2739 	enum drbd_conns cstate;
2740 	enum drbd_state_rv rv;
2741 
2742 repeat:
2743 	rv = conn_request_state(connection, NS(conn, C_DISCONNECTING),
2744 			force ? CS_HARD : 0);
2745 
2746 	switch (rv) {
2747 	case SS_NOTHING_TO_DO:
2748 		break;
2749 	case SS_ALREADY_STANDALONE:
2750 		return SS_SUCCESS;
2751 	case SS_PRIMARY_NOP:
2752 		/* Our state checking code wants to see the peer outdated. */
2753 		rv = conn_request_state(connection, NS2(conn, C_DISCONNECTING, pdsk, D_OUTDATED), 0);
2754 
2755 		if (rv == SS_OUTDATE_WO_CONN) /* lost connection before graceful disconnect succeeded */
2756 			rv = conn_request_state(connection, NS(conn, C_DISCONNECTING), CS_VERBOSE);
2757 
2758 		break;
2759 	case SS_CW_FAILED_BY_PEER:
2760 		spin_lock_irq(&connection->resource->req_lock);
2761 		cstate = connection->cstate;
2762 		spin_unlock_irq(&connection->resource->req_lock);
2763 		if (cstate <= C_WF_CONNECTION)
2764 			goto repeat;
2765 		/* The peer probably wants to see us outdated. */
2766 		rv = conn_request_state(connection, NS2(conn, C_DISCONNECTING,
2767 							disk, D_OUTDATED), 0);
2768 		if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2769 			rv = conn_request_state(connection, NS(conn, C_DISCONNECTING),
2770 					CS_HARD);
2771 		}
2772 		break;
2773 	default:;
2774 		/* no special handling necessary */
2775 	}
2776 
2777 	if (rv >= SS_SUCCESS) {
2778 		enum drbd_state_rv rv2;
2779 		/* No one else can reconfigure the network while I am here.
2780 		 * The state handling only uses drbd_thread_stop_nowait(),
2781 		 * we want to really wait here until the receiver is no more.
2782 		 */
2783 		drbd_thread_stop(&connection->receiver);
2784 
2785 		/* Race breaker.  This additional state change request may be
2786 		 * necessary, if this was a forced disconnect during a receiver
2787 		 * restart.  We may have "killed" the receiver thread just
2788 		 * after drbd_receiver() returned.  Typically, we should be
2789 		 * C_STANDALONE already, now, and this becomes a no-op.
2790 		 */
2791 		rv2 = conn_request_state(connection, NS(conn, C_STANDALONE),
2792 				CS_VERBOSE | CS_HARD);
2793 		if (rv2 < SS_SUCCESS)
2794 			drbd_err(connection,
2795 				"unexpected rv2=%d in conn_try_disconnect()\n",
2796 				rv2);
2797 		/* Unlike in DRBD 9, the state engine has generated
2798 		 * NOTIFY_DESTROY events before clearing connection->net_conf. */
2799 	}
2800 	return rv;
2801 }
2802 
2803 int drbd_nl_disconnect_doit(struct sk_buff *skb, struct genl_info *info)
2804 {
2805 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2806 	struct disconnect_parms parms;
2807 	struct drbd_connection *connection;
2808 	enum drbd_state_rv rv;
2809 	enum drbd_ret_code retcode;
2810 	int err;
2811 
2812 	if (!adm_ctx->reply_skb)
2813 		return 0;
2814 	retcode = adm_ctx->reply_dh->ret_code;
2815 	if (retcode != NO_ERROR)
2816 		goto fail;
2817 
2818 	connection = adm_ctx->connection;
2819 	memset(&parms, 0, sizeof(parms));
2820 	if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2821 		err = disconnect_parms_from_attrs(&parms, info);
2822 		if (err) {
2823 			retcode = ERR_MANDATORY_TAG;
2824 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
2825 			goto fail;
2826 		}
2827 	}
2828 
2829 	mutex_lock(&adm_ctx->resource->adm_mutex);
2830 	rv = conn_try_disconnect(connection, parms.force_disconnect);
2831 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2832 	if (rv < SS_SUCCESS) {
2833 		adm_ctx->reply_dh->ret_code = rv;
2834 		return 0;
2835 	}
2836 	retcode = NO_ERROR;
2837  fail:
2838 	adm_ctx->reply_dh->ret_code = retcode;
2839 	return 0;
2840 }
2841 
2842 void resync_after_online_grow(struct drbd_device *device)
2843 {
2844 	int iass; /* I am sync source */
2845 
2846 	drbd_info(device, "Resync of new storage after online grow\n");
2847 	if (device->state.role != device->state.peer)
2848 		iass = (device->state.role == R_PRIMARY);
2849 	else
2850 		iass = test_bit(RESOLVE_CONFLICTS, &first_peer_device(device)->connection->flags);
2851 
2852 	if (iass)
2853 		drbd_start_resync(device, C_SYNC_SOURCE);
2854 	else
2855 		_drbd_request_state(device, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2856 }
2857 
2858 int drbd_nl_resize_doit(struct sk_buff *skb, struct genl_info *info)
2859 {
2860 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2861 	struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2862 	struct resize_parms rs;
2863 	struct drbd_device *device;
2864 	enum drbd_ret_code retcode;
2865 	enum determine_dev_size dd;
2866 	bool change_al_layout = false;
2867 	enum dds_flags ddsf;
2868 	sector_t u_size;
2869 	int err;
2870 
2871 	if (!adm_ctx->reply_skb)
2872 		return 0;
2873 	retcode = adm_ctx->reply_dh->ret_code;
2874 	if (retcode != NO_ERROR)
2875 		goto finish;
2876 
2877 	mutex_lock(&adm_ctx->resource->adm_mutex);
2878 	device = adm_ctx->device;
2879 	if (!get_ldev(device)) {
2880 		retcode = ERR_NO_DISK;
2881 		goto fail;
2882 	}
2883 
2884 	memset(&rs, 0, sizeof(struct resize_parms));
2885 	rs.al_stripes = device->ldev->md.al_stripes;
2886 	rs.al_stripe_size = device->ldev->md.al_stripe_size_4k * 4;
2887 	if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2888 		err = resize_parms_from_attrs(&rs, info);
2889 		if (err) {
2890 			retcode = ERR_MANDATORY_TAG;
2891 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
2892 			goto fail_ldev;
2893 		}
2894 	}
2895 
2896 	if (device->state.conn > C_CONNECTED) {
2897 		retcode = ERR_RESIZE_RESYNC;
2898 		goto fail_ldev;
2899 	}
2900 
2901 	if (device->state.role == R_SECONDARY &&
2902 	    device->state.peer == R_SECONDARY) {
2903 		retcode = ERR_NO_PRIMARY;
2904 		goto fail_ldev;
2905 	}
2906 
2907 	if (rs.no_resync && first_peer_device(device)->connection->agreed_pro_version < 93) {
2908 		retcode = ERR_NEED_APV_93;
2909 		goto fail_ldev;
2910 	}
2911 
2912 	rcu_read_lock();
2913 	u_size = rcu_dereference(device->ldev->disk_conf)->disk_size;
2914 	rcu_read_unlock();
2915 	if (u_size != (sector_t)rs.resize_size) {
2916 		new_disk_conf = kmalloc_obj(struct disk_conf);
2917 		if (!new_disk_conf) {
2918 			retcode = ERR_NOMEM;
2919 			goto fail_ldev;
2920 		}
2921 	}
2922 
2923 	if (device->ldev->md.al_stripes != rs.al_stripes ||
2924 	    device->ldev->md.al_stripe_size_4k != rs.al_stripe_size / 4) {
2925 		u32 al_size_k = rs.al_stripes * rs.al_stripe_size;
2926 
2927 		if (al_size_k > (16 * 1024 * 1024)) {
2928 			retcode = ERR_MD_LAYOUT_TOO_BIG;
2929 			goto fail_ldev;
2930 		}
2931 
2932 		if (al_size_k < MD_32kB_SECT/2) {
2933 			retcode = ERR_MD_LAYOUT_TOO_SMALL;
2934 			goto fail_ldev;
2935 		}
2936 
2937 		if (device->state.conn != C_CONNECTED && !rs.resize_force) {
2938 			retcode = ERR_MD_LAYOUT_CONNECTED;
2939 			goto fail_ldev;
2940 		}
2941 
2942 		change_al_layout = true;
2943 	}
2944 
2945 	if (device->ldev->known_size != drbd_get_capacity(device->ldev->backing_bdev))
2946 		device->ldev->known_size = drbd_get_capacity(device->ldev->backing_bdev);
2947 
2948 	if (new_disk_conf) {
2949 		mutex_lock(&device->resource->conf_update);
2950 		old_disk_conf = device->ldev->disk_conf;
2951 		*new_disk_conf = *old_disk_conf;
2952 		new_disk_conf->disk_size = (sector_t)rs.resize_size;
2953 		rcu_assign_pointer(device->ldev->disk_conf, new_disk_conf);
2954 		mutex_unlock(&device->resource->conf_update);
2955 		kvfree_rcu_mightsleep(old_disk_conf);
2956 		new_disk_conf = NULL;
2957 	}
2958 
2959 	ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2960 	dd = drbd_determine_dev_size(device, ddsf, change_al_layout ? &rs : NULL);
2961 	drbd_md_sync(device);
2962 	put_ldev(device);
2963 	if (dd == DS_ERROR) {
2964 		retcode = ERR_NOMEM_BITMAP;
2965 		goto fail;
2966 	} else if (dd == DS_ERROR_SPACE_MD) {
2967 		retcode = ERR_MD_LAYOUT_NO_FIT;
2968 		goto fail;
2969 	} else if (dd == DS_ERROR_SHRINK) {
2970 		retcode = ERR_IMPLICIT_SHRINK;
2971 		goto fail;
2972 	}
2973 
2974 	if (device->state.conn == C_CONNECTED) {
2975 		if (dd == DS_GREW)
2976 			set_bit(RESIZE_PENDING, &device->flags);
2977 
2978 		drbd_send_uuids(first_peer_device(device));
2979 		drbd_send_sizes(first_peer_device(device), 1, ddsf);
2980 	}
2981 
2982  fail:
2983 	mutex_unlock(&adm_ctx->resource->adm_mutex);
2984  finish:
2985 	adm_ctx->reply_dh->ret_code = retcode;
2986 	return 0;
2987 
2988  fail_ldev:
2989 	put_ldev(device);
2990 	kfree(new_disk_conf);
2991 	goto fail;
2992 }
2993 
2994 int drbd_nl_resource_opts_doit(struct sk_buff *skb, struct genl_info *info)
2995 {
2996 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
2997 	enum drbd_ret_code retcode;
2998 	struct res_opts res_opts;
2999 	int err;
3000 
3001 	if (!adm_ctx->reply_skb)
3002 		return 0;
3003 	retcode = adm_ctx->reply_dh->ret_code;
3004 	if (retcode != NO_ERROR)
3005 		goto fail;
3006 
3007 	res_opts = adm_ctx->resource->res_opts;
3008 	if (should_set_defaults(info))
3009 		set_res_opts_defaults(&res_opts);
3010 
3011 	err = res_opts_from_attrs(&res_opts, info);
3012 	if (err && err != -ENOMSG) {
3013 		retcode = ERR_MANDATORY_TAG;
3014 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
3015 		goto fail;
3016 	}
3017 
3018 	mutex_lock(&adm_ctx->resource->adm_mutex);
3019 	err = set_resource_options(adm_ctx->resource, &res_opts);
3020 	if (err) {
3021 		retcode = ERR_INVALID_REQUEST;
3022 		if (err == -ENOMEM)
3023 			retcode = ERR_NOMEM;
3024 	}
3025 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3026 
3027 fail:
3028 	adm_ctx->reply_dh->ret_code = retcode;
3029 	return 0;
3030 }
3031 
3032 int drbd_nl_invalidate_doit(struct sk_buff *skb, struct genl_info *info)
3033 {
3034 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3035 	struct drbd_device *device;
3036 	int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3037 
3038 	if (!adm_ctx->reply_skb)
3039 		return 0;
3040 	retcode = adm_ctx->reply_dh->ret_code;
3041 	if (retcode != NO_ERROR)
3042 		goto out;
3043 
3044 	device = adm_ctx->device;
3045 	if (!get_ldev(device)) {
3046 		retcode = ERR_NO_DISK;
3047 		goto out;
3048 	}
3049 
3050 	mutex_lock(&adm_ctx->resource->adm_mutex);
3051 
3052 	/* If there is still bitmap IO pending, probably because of a previous
3053 	 * resync just being finished, wait for it before requesting a new resync.
3054 	 * Also wait for it's after_state_ch(). */
3055 	drbd_suspend_io(device);
3056 	wait_event(device->misc_wait, !test_bit(BITMAP_IO, &device->flags));
3057 	drbd_flush_workqueue(&first_peer_device(device)->connection->sender_work);
3058 
3059 	/* If we happen to be C_STANDALONE R_SECONDARY, just change to
3060 	 * D_INCONSISTENT, and set all bits in the bitmap.  Otherwise,
3061 	 * try to start a resync handshake as sync target for full sync.
3062 	 */
3063 	if (device->state.conn == C_STANDALONE && device->state.role == R_SECONDARY) {
3064 		retcode = drbd_request_state(device, NS(disk, D_INCONSISTENT));
3065 		if (retcode >= SS_SUCCESS) {
3066 			if (drbd_bitmap_io(device, &drbd_bmio_set_n_write,
3067 				"set_n_write from invalidate", BM_LOCKED_MASK, NULL))
3068 				retcode = ERR_IO_MD_DISK;
3069 		}
3070 	} else
3071 		retcode = drbd_request_state(device, NS(conn, C_STARTING_SYNC_T));
3072 	drbd_resume_io(device);
3073 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3074 	put_ldev(device);
3075 out:
3076 	adm_ctx->reply_dh->ret_code = retcode;
3077 	return 0;
3078 }
3079 
3080 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
3081 		union drbd_state mask, union drbd_state val)
3082 {
3083 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3084 	enum drbd_ret_code retcode;
3085 
3086 	if (!adm_ctx->reply_skb)
3087 		return 0;
3088 	retcode = adm_ctx->reply_dh->ret_code;
3089 	if (retcode != NO_ERROR)
3090 		goto out;
3091 
3092 	mutex_lock(&adm_ctx->resource->adm_mutex);
3093 	retcode = drbd_request_state(adm_ctx->device, mask, val);
3094 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3095 out:
3096 	adm_ctx->reply_dh->ret_code = retcode;
3097 	return 0;
3098 }
3099 
3100 static int drbd_bmio_set_susp_al(struct drbd_device *device,
3101 		struct drbd_peer_device *peer_device) __must_hold(local)
3102 {
3103 	int rv;
3104 
3105 	rv = drbd_bmio_set_n_write(device, peer_device);
3106 	drbd_suspend_al(device);
3107 	return rv;
3108 }
3109 
3110 int drbd_nl_inval_peer_doit(struct sk_buff *skb, struct genl_info *info)
3111 {
3112 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3113 	int retcode; /* drbd_ret_code, drbd_state_rv */
3114 	struct drbd_device *device;
3115 
3116 	if (!adm_ctx->reply_skb)
3117 		return 0;
3118 	retcode = adm_ctx->reply_dh->ret_code;
3119 	if (retcode != NO_ERROR)
3120 		goto out;
3121 
3122 	device = adm_ctx->device;
3123 	if (!get_ldev(device)) {
3124 		retcode = ERR_NO_DISK;
3125 		goto out;
3126 	}
3127 
3128 	mutex_lock(&adm_ctx->resource->adm_mutex);
3129 
3130 	/* If there is still bitmap IO pending, probably because of a previous
3131 	 * resync just being finished, wait for it before requesting a new resync.
3132 	 * Also wait for it's after_state_ch(). */
3133 	drbd_suspend_io(device);
3134 	wait_event(device->misc_wait, !test_bit(BITMAP_IO, &device->flags));
3135 	drbd_flush_workqueue(&first_peer_device(device)->connection->sender_work);
3136 
3137 	/* If we happen to be C_STANDALONE R_PRIMARY, just set all bits
3138 	 * in the bitmap.  Otherwise, try to start a resync handshake
3139 	 * as sync source for full sync.
3140 	 */
3141 	if (device->state.conn == C_STANDALONE && device->state.role == R_PRIMARY) {
3142 		/* The peer will get a resync upon connect anyways. Just make that
3143 		   into a full resync. */
3144 		retcode = drbd_request_state(device, NS(pdsk, D_INCONSISTENT));
3145 		if (retcode >= SS_SUCCESS) {
3146 			if (drbd_bitmap_io(device, &drbd_bmio_set_susp_al,
3147 				"set_n_write from invalidate_peer",
3148 				BM_LOCKED_SET_ALLOWED, NULL))
3149 				retcode = ERR_IO_MD_DISK;
3150 		}
3151 	} else
3152 		retcode = drbd_request_state(device, NS(conn, C_STARTING_SYNC_S));
3153 	drbd_resume_io(device);
3154 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3155 	put_ldev(device);
3156 out:
3157 	adm_ctx->reply_dh->ret_code = retcode;
3158 	return 0;
3159 }
3160 
3161 int drbd_nl_pause_sync_doit(struct sk_buff *skb, struct genl_info *info)
3162 {
3163 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3164 	enum drbd_ret_code retcode;
3165 
3166 	if (!adm_ctx->reply_skb)
3167 		return 0;
3168 	retcode = adm_ctx->reply_dh->ret_code;
3169 	if (retcode != NO_ERROR)
3170 		goto out;
3171 
3172 	mutex_lock(&adm_ctx->resource->adm_mutex);
3173 	if (drbd_request_state(adm_ctx->device, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
3174 		retcode = ERR_PAUSE_IS_SET;
3175 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3176 out:
3177 	adm_ctx->reply_dh->ret_code = retcode;
3178 	return 0;
3179 }
3180 
3181 int drbd_nl_resume_sync_doit(struct sk_buff *skb, struct genl_info *info)
3182 {
3183 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3184 	union drbd_dev_state s;
3185 	enum drbd_ret_code retcode;
3186 
3187 	if (!adm_ctx->reply_skb)
3188 		return 0;
3189 	retcode = adm_ctx->reply_dh->ret_code;
3190 	if (retcode != NO_ERROR)
3191 		goto out;
3192 
3193 	mutex_lock(&adm_ctx->resource->adm_mutex);
3194 	if (drbd_request_state(adm_ctx->device, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
3195 		s = adm_ctx->device->state;
3196 		if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
3197 			retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
3198 				  s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
3199 		} else {
3200 			retcode = ERR_PAUSE_IS_CLEAR;
3201 		}
3202 	}
3203 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3204 out:
3205 	adm_ctx->reply_dh->ret_code = retcode;
3206 	return 0;
3207 }
3208 
3209 int drbd_nl_suspend_io_doit(struct sk_buff *skb, struct genl_info *info)
3210 {
3211 	return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
3212 }
3213 
3214 int drbd_nl_resume_io_doit(struct sk_buff *skb, struct genl_info *info)
3215 {
3216 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3217 	struct drbd_device *device;
3218 	int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3219 
3220 	if (!adm_ctx->reply_skb)
3221 		return 0;
3222 	retcode = adm_ctx->reply_dh->ret_code;
3223 	if (retcode != NO_ERROR)
3224 		goto out;
3225 
3226 	mutex_lock(&adm_ctx->resource->adm_mutex);
3227 	device = adm_ctx->device;
3228 	if (test_bit(NEW_CUR_UUID, &device->flags)) {
3229 		if (get_ldev_if_state(device, D_ATTACHING)) {
3230 			drbd_uuid_new_current(device);
3231 			put_ldev(device);
3232 		} else {
3233 			/* This is effectively a multi-stage "forced down".
3234 			 * The NEW_CUR_UUID bit is supposedly only set, if we
3235 			 * lost the replication connection, and are configured
3236 			 * to freeze IO and wait for some fence-peer handler.
3237 			 * So we still don't have a replication connection.
3238 			 * And now we don't have a local disk either.  After
3239 			 * resume, we will fail all pending and new IO, because
3240 			 * we don't have any data anymore.  Which means we will
3241 			 * eventually be able to terminate all users of this
3242 			 * device, and then take it down.  By bumping the
3243 			 * "effective" data uuid, we make sure that you really
3244 			 * need to tear down before you reconfigure, we will
3245 			 * the refuse to re-connect or re-attach (because no
3246 			 * matching real data uuid exists).
3247 			 */
3248 			u64 val;
3249 			val = get_random_u64();
3250 			drbd_set_ed_uuid(device, val);
3251 			drbd_warn(device, "Resumed without access to data; please tear down before attempting to re-configure.\n");
3252 		}
3253 		clear_bit(NEW_CUR_UUID, &device->flags);
3254 	}
3255 	drbd_suspend_io(device);
3256 	retcode = drbd_request_state(device, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
3257 	if (retcode == SS_SUCCESS) {
3258 		if (device->state.conn < C_CONNECTED)
3259 			tl_clear(first_peer_device(device)->connection);
3260 		if (device->state.disk == D_DISKLESS || device->state.disk == D_FAILED)
3261 			tl_restart(first_peer_device(device)->connection, FAIL_FROZEN_DISK_IO);
3262 	}
3263 	drbd_resume_io(device);
3264 	mutex_unlock(&adm_ctx->resource->adm_mutex);
3265 out:
3266 	adm_ctx->reply_dh->ret_code = retcode;
3267 	return 0;
3268 }
3269 
3270 int drbd_nl_outdate_doit(struct sk_buff *skb, struct genl_info *info)
3271 {
3272 	return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
3273 }
3274 
3275 static int nla_put_drbd_cfg_context(struct sk_buff *skb,
3276 				    struct drbd_resource *resource,
3277 				    struct drbd_connection *connection,
3278 				    struct drbd_device *device)
3279 {
3280 	struct nlattr *nla;
3281 	nla = nla_nest_start_noflag(skb, DRBD_NLA_CFG_CONTEXT);
3282 	if (!nla)
3283 		goto nla_put_failure;
3284 	if (device &&
3285 	    nla_put_u32(skb, DRBD_A_DRBD_CFG_CONTEXT_CTX_VOLUME, device->vnr))
3286 		goto nla_put_failure;
3287 	if (nla_put_string(skb, DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME, resource->name))
3288 		goto nla_put_failure;
3289 	if (connection) {
3290 		if (connection->my_addr_len &&
3291 		    nla_put(skb, DRBD_A_DRBD_CFG_CONTEXT_CTX_MY_ADDR,
3292 			    connection->my_addr_len,
3293 			    &connection->my_addr))
3294 			goto nla_put_failure;
3295 		if (connection->peer_addr_len &&
3296 		    nla_put(skb, DRBD_A_DRBD_CFG_CONTEXT_CTX_PEER_ADDR,
3297 			    connection->peer_addr_len,
3298 			    &connection->peer_addr))
3299 			goto nla_put_failure;
3300 	}
3301 	nla_nest_end(skb, nla);
3302 	return 0;
3303 
3304 nla_put_failure:
3305 	if (nla)
3306 		nla_nest_cancel(skb, nla);
3307 	return -EMSGSIZE;
3308 }
3309 
3310 /*
3311  * net_conf_to_skb() serializes the shared secret verbatim. Any path that can
3312  * answer a request from an unprivileged process must pass exclude_sensitive,
3313  * so the secret is blanked in a private copy before it reaches the skb.
3314  */
3315 static int net_conf_to_skb_sanitized(struct sk_buff *skb, struct net_conf *nc,
3316 				     bool exclude_sensitive)
3317 {
3318 	struct net_conf nc_clean;
3319 
3320 	if (!exclude_sensitive)
3321 		return net_conf_to_skb(skb, nc);
3322 
3323 	nc_clean = *nc;
3324 	memset(nc_clean.shared_secret, 0, sizeof(nc_clean.shared_secret));
3325 	nc_clean.shared_secret_len = 0;
3326 
3327 	return net_conf_to_skb(skb, &nc_clean);
3328 }
3329 
3330 /*
3331  * The generic netlink dump callbacks are called outside the genl_lock(), so
3332  * they cannot use the simple attribute parsing code which uses global
3333  * attribute tables.
3334  */
3335 static struct nlattr *find_cfg_context_attr(const struct nlmsghdr *nlh, int attr)
3336 {
3337 	const unsigned int hdrlen = GENL_HDRLEN + sizeof(struct drbd_genlmsghdr);
3338 	struct nlattr *nla;
3339 
3340 	nla = nla_find(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen),
3341 		       DRBD_NLA_CFG_CONTEXT);
3342 	if (!nla)
3343 		return NULL;
3344 	return nla_find_nested(nla, attr);
3345 }
3346 
3347 static void resource_to_info(struct resource_info *, struct drbd_resource *);
3348 
3349 int drbd_nl_get_resources_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
3350 {
3351 	struct drbd_genlmsghdr *dh;
3352 	struct drbd_resource *resource;
3353 	struct resource_info resource_info;
3354 	struct resource_statistics resource_statistics;
3355 	int err;
3356 
3357 	rcu_read_lock();
3358 	if (cb->args[0]) {
3359 		for_each_resource_rcu(resource, &drbd_resources)
3360 			if (resource == (struct drbd_resource *)cb->args[0])
3361 				goto found_resource;
3362 		err = 0;  /* resource was probably deleted */
3363 		goto out;
3364 	}
3365 	resource = list_entry(&drbd_resources,
3366 			      struct drbd_resource, resources);
3367 
3368 found_resource:
3369 	list_for_each_entry_continue_rcu(resource, &drbd_resources, resources) {
3370 		goto put_result;
3371 	}
3372 	err = 0;
3373 	goto out;
3374 
3375 put_result:
3376 	dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
3377 			cb->nlh->nlmsg_seq, &drbd_nl_family,
3378 			NLM_F_MULTI, DRBD_ADM_GET_RESOURCES);
3379 	err = -ENOMEM;
3380 	if (!dh)
3381 		goto out;
3382 	dh->minor = -1U;
3383 	dh->ret_code = NO_ERROR;
3384 	err = nla_put_drbd_cfg_context(skb, resource, NULL, NULL);
3385 	if (err)
3386 		goto out;
3387 	err = res_opts_to_skb(skb, &resource->res_opts);
3388 	if (err)
3389 		goto out;
3390 	resource_to_info(&resource_info, resource);
3391 	err = resource_info_to_skb(skb, &resource_info);
3392 	if (err)
3393 		goto out;
3394 	resource_statistics.res_stat_write_ordering = resource->write_ordering;
3395 	err = resource_statistics_to_skb(skb, &resource_statistics);
3396 	if (err)
3397 		goto out;
3398 	cb->args[0] = (long)resource;
3399 	genlmsg_end(skb, dh);
3400 	err = 0;
3401 
3402 out:
3403 	rcu_read_unlock();
3404 	if (err)
3405 		return err;
3406 	return skb->len;
3407 }
3408 
3409 static void device_to_statistics(struct device_statistics *s,
3410 				 struct drbd_device *device)
3411 {
3412 	memset(s, 0, sizeof(*s));
3413 	s->dev_upper_blocked = !may_inc_ap_bio(device);
3414 	if (get_ldev(device)) {
3415 		struct drbd_md *md = &device->ldev->md;
3416 		u64 *history_uuids = (u64 *)s->history_uuids;
3417 		int n;
3418 
3419 		spin_lock_irq(&md->uuid_lock);
3420 		s->dev_current_uuid = md->uuid[UI_CURRENT];
3421 		BUILD_BUG_ON(sizeof(s->history_uuids) < UI_HISTORY_END - UI_HISTORY_START + 1);
3422 		for (n = 0; n < UI_HISTORY_END - UI_HISTORY_START + 1; n++)
3423 			history_uuids[n] = md->uuid[UI_HISTORY_START + n];
3424 		for (; n < HISTORY_UUIDS; n++)
3425 			history_uuids[n] = 0;
3426 		s->history_uuids_len = HISTORY_UUIDS;
3427 		spin_unlock_irq(&md->uuid_lock);
3428 
3429 		s->dev_disk_flags = md->flags;
3430 		put_ldev(device);
3431 	}
3432 	s->dev_size = get_capacity(device->vdisk);
3433 	s->dev_read = device->read_cnt;
3434 	s->dev_write = device->writ_cnt;
3435 	s->dev_al_writes = device->al_writ_cnt;
3436 	s->dev_bm_writes = device->bm_writ_cnt;
3437 	s->dev_upper_pending = atomic_read(&device->ap_bio_cnt);
3438 	s->dev_lower_pending = atomic_read(&device->local_cnt);
3439 	s->dev_al_suspended = test_bit(AL_SUSPENDED, &device->flags);
3440 	s->dev_exposed_data_uuid = device->ed_uuid;
3441 }
3442 
3443 static int put_resource_in_arg0(struct netlink_callback *cb, int holder_nr)
3444 {
3445 	if (cb->args[0]) {
3446 		struct drbd_resource *resource =
3447 			(struct drbd_resource *)cb->args[0];
3448 		kref_put(&resource->kref, drbd_destroy_resource);
3449 	}
3450 
3451 	return 0;
3452 }
3453 
3454 int drbd_adm_dump_devices_done(struct netlink_callback *cb) {
3455 	return put_resource_in_arg0(cb, 7);
3456 }
3457 
3458 static void device_to_info(struct device_info *, struct drbd_device *);
3459 
3460 int drbd_nl_get_devices_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
3461 {
3462 	struct nlattr *resource_filter;
3463 	struct drbd_resource *resource;
3464 	struct drbd_device *device;
3465 	int minor, err, retcode;
3466 	struct drbd_genlmsghdr *dh;
3467 	struct device_info device_info;
3468 	struct device_statistics device_statistics;
3469 	struct idr *idr_to_search;
3470 
3471 	resource = (struct drbd_resource *)cb->args[0];
3472 	if (!cb->args[0] && !cb->args[1]) {
3473 		resource_filter = find_cfg_context_attr(cb->nlh,
3474 				DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME);
3475 		if (resource_filter) {
3476 			retcode = ERR_RES_NOT_KNOWN;
3477 			resource = drbd_find_resource(nla_data(resource_filter));
3478 			if (!resource) {
3479 				rcu_read_lock();
3480 				goto put_result;
3481 			}
3482 			cb->args[0] = (long)resource;
3483 		}
3484 	}
3485 
3486 	rcu_read_lock();
3487 	minor = cb->args[1];
3488 	idr_to_search = resource ? &resource->devices : &drbd_devices;
3489 	device = idr_get_next(idr_to_search, &minor);
3490 	if (!device) {
3491 		err = 0;
3492 		goto out;
3493 	}
3494 	idr_for_each_entry_continue(idr_to_search, device, minor) {
3495 		retcode = NO_ERROR;
3496 		goto put_result;  /* only one iteration */
3497 	}
3498 	err = 0;
3499 	goto out;  /* no more devices */
3500 
3501 put_result:
3502 	dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
3503 			cb->nlh->nlmsg_seq, &drbd_nl_family,
3504 			NLM_F_MULTI, DRBD_ADM_GET_DEVICES);
3505 	err = -ENOMEM;
3506 	if (!dh)
3507 		goto out;
3508 	dh->ret_code = retcode;
3509 	dh->minor = -1U;
3510 	if (retcode == NO_ERROR) {
3511 		dh->minor = device->minor;
3512 		err = nla_put_drbd_cfg_context(skb, device->resource, NULL, device);
3513 		if (err)
3514 			goto out;
3515 		if (get_ldev(device)) {
3516 			struct disk_conf *disk_conf =
3517 				rcu_dereference(device->ldev->disk_conf);
3518 
3519 			err = disk_conf_to_skb(skb, disk_conf);
3520 			put_ldev(device);
3521 			if (err)
3522 				goto out;
3523 		}
3524 		device_to_info(&device_info, device);
3525 		err = device_info_to_skb(skb, &device_info);
3526 		if (err)
3527 			goto out;
3528 
3529 		device_to_statistics(&device_statistics, device);
3530 		err = device_statistics_to_skb(skb, &device_statistics);
3531 		if (err)
3532 			goto out;
3533 		cb->args[1] = minor + 1;
3534 	}
3535 	genlmsg_end(skb, dh);
3536 	err = 0;
3537 
3538 out:
3539 	rcu_read_unlock();
3540 	if (err)
3541 		return err;
3542 	return skb->len;
3543 }
3544 
3545 int drbd_adm_dump_connections_done(struct netlink_callback *cb)
3546 {
3547 	return put_resource_in_arg0(cb, 6);
3548 }
3549 
3550 enum { SINGLE_RESOURCE, ITERATE_RESOURCES };
3551 
3552 int drbd_nl_get_connections_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
3553 {
3554 	struct nlattr *resource_filter;
3555 	struct drbd_resource *resource = NULL, *next_resource;
3556 	struct drbd_connection *connection;
3557 	int err = 0, retcode;
3558 	struct drbd_genlmsghdr *dh;
3559 	struct connection_info connection_info;
3560 	struct connection_statistics connection_statistics;
3561 
3562 	rcu_read_lock();
3563 	resource = (struct drbd_resource *)cb->args[0];
3564 	if (!cb->args[0]) {
3565 		resource_filter = find_cfg_context_attr(cb->nlh,
3566 				DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME);
3567 		if (resource_filter) {
3568 			retcode = ERR_RES_NOT_KNOWN;
3569 			resource = drbd_find_resource(nla_data(resource_filter));
3570 			if (!resource)
3571 				goto put_result;
3572 			cb->args[0] = (long)resource;
3573 			cb->args[1] = SINGLE_RESOURCE;
3574 		}
3575 	}
3576 	if (!resource) {
3577 		if (list_empty(&drbd_resources))
3578 			goto out;
3579 		resource = list_first_entry(&drbd_resources, struct drbd_resource, resources);
3580 		kref_get(&resource->kref);
3581 		cb->args[0] = (long)resource;
3582 		cb->args[1] = ITERATE_RESOURCES;
3583 	}
3584 
3585     next_resource:
3586 	rcu_read_unlock();
3587 	mutex_lock(&resource->conf_update);
3588 	rcu_read_lock();
3589 	if (cb->args[2]) {
3590 		for_each_connection_rcu(connection, resource)
3591 			if (connection == (struct drbd_connection *)cb->args[2])
3592 				goto found_connection;
3593 		/* connection was probably deleted */
3594 		goto no_more_connections;
3595 	}
3596 	connection = list_entry(&resource->connections, struct drbd_connection, connections);
3597 
3598 found_connection:
3599 	list_for_each_entry_continue_rcu(connection, &resource->connections, connections) {
3600 		if (!has_net_conf(connection))
3601 			continue;
3602 		retcode = NO_ERROR;
3603 		goto put_result;  /* only one iteration */
3604 	}
3605 
3606 no_more_connections:
3607 	if (cb->args[1] == ITERATE_RESOURCES) {
3608 		for_each_resource_rcu(next_resource, &drbd_resources) {
3609 			if (next_resource == resource)
3610 				goto found_resource;
3611 		}
3612 		/* resource was probably deleted */
3613 	}
3614 	goto out;
3615 
3616 found_resource:
3617 	list_for_each_entry_continue_rcu(next_resource, &drbd_resources, resources) {
3618 		mutex_unlock(&resource->conf_update);
3619 		kref_put(&resource->kref, drbd_destroy_resource);
3620 		resource = next_resource;
3621 		kref_get(&resource->kref);
3622 		cb->args[0] = (long)resource;
3623 		cb->args[2] = 0;
3624 		goto next_resource;
3625 	}
3626 	goto out;  /* no more resources */
3627 
3628 put_result:
3629 	dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
3630 			cb->nlh->nlmsg_seq, &drbd_nl_family,
3631 			NLM_F_MULTI, DRBD_ADM_GET_CONNECTIONS);
3632 	err = -ENOMEM;
3633 	if (!dh)
3634 		goto out;
3635 	dh->ret_code = retcode;
3636 	dh->minor = -1U;
3637 	if (retcode == NO_ERROR) {
3638 		struct net_conf *net_conf;
3639 
3640 		err = nla_put_drbd_cfg_context(skb, resource, connection, NULL);
3641 		if (err)
3642 			goto out;
3643 		net_conf = rcu_dereference(connection->net_conf);
3644 		if (net_conf) {
3645 			err = net_conf_to_skb_sanitized(skb, net_conf,
3646 							!capable(CAP_SYS_ADMIN));
3647 			if (err)
3648 				goto out;
3649 		}
3650 		connection_to_info(&connection_info, connection);
3651 		err = connection_info_to_skb(skb, &connection_info);
3652 		if (err)
3653 			goto out;
3654 		connection_statistics.conn_congested = test_bit(NET_CONGESTED, &connection->flags);
3655 		err = connection_statistics_to_skb(skb, &connection_statistics);
3656 		if (err)
3657 			goto out;
3658 		cb->args[2] = (long)connection;
3659 	}
3660 	genlmsg_end(skb, dh);
3661 	err = 0;
3662 
3663 out:
3664 	rcu_read_unlock();
3665 	if (resource)
3666 		mutex_unlock(&resource->conf_update);
3667 	if (err)
3668 		return err;
3669 	return skb->len;
3670 }
3671 
3672 enum mdf_peer_flag {
3673 	MDF_PEER_CONNECTED =	1 << 0,
3674 	MDF_PEER_OUTDATED =	1 << 1,
3675 	MDF_PEER_FENCING =	1 << 2,
3676 	MDF_PEER_FULL_SYNC =	1 << 3,
3677 };
3678 
3679 static void peer_device_to_statistics(struct peer_device_statistics *s,
3680 				      struct drbd_peer_device *peer_device)
3681 {
3682 	struct drbd_device *device = peer_device->device;
3683 
3684 	memset(s, 0, sizeof(*s));
3685 	s->peer_dev_received = device->recv_cnt;
3686 	s->peer_dev_sent = device->send_cnt;
3687 	s->peer_dev_pending = atomic_read(&device->ap_pending_cnt) +
3688 			      atomic_read(&device->rs_pending_cnt);
3689 	s->peer_dev_unacked = atomic_read(&device->unacked_cnt);
3690 	s->peer_dev_out_of_sync = drbd_bm_total_weight(device) << (BM_BLOCK_SHIFT - 9);
3691 	s->peer_dev_resync_failed = device->rs_failed << (BM_BLOCK_SHIFT - 9);
3692 	if (get_ldev(device)) {
3693 		struct drbd_md *md = &device->ldev->md;
3694 
3695 		spin_lock_irq(&md->uuid_lock);
3696 		s->peer_dev_bitmap_uuid = md->uuid[UI_BITMAP];
3697 		spin_unlock_irq(&md->uuid_lock);
3698 		s->peer_dev_flags =
3699 			(drbd_md_test_flag(device->ldev, MDF_CONNECTED_IND) ?
3700 				MDF_PEER_CONNECTED : 0) +
3701 			(drbd_md_test_flag(device->ldev, MDF_CONSISTENT) &&
3702 			 !drbd_md_test_flag(device->ldev, MDF_WAS_UP_TO_DATE) ?
3703 				MDF_PEER_OUTDATED : 0) +
3704 			/* FIXME: MDF_PEER_FENCING? */
3705 			(drbd_md_test_flag(device->ldev, MDF_FULL_SYNC) ?
3706 				MDF_PEER_FULL_SYNC : 0);
3707 		put_ldev(device);
3708 	}
3709 }
3710 
3711 int drbd_adm_dump_peer_devices_done(struct netlink_callback *cb)
3712 {
3713 	return put_resource_in_arg0(cb, 9);
3714 }
3715 
3716 int drbd_nl_get_peer_devices_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
3717 {
3718 	struct nlattr *resource_filter;
3719 	struct drbd_resource *resource;
3720 	struct drbd_device *device;
3721 	struct drbd_peer_device *peer_device = NULL;
3722 	int minor, err, retcode;
3723 	struct drbd_genlmsghdr *dh;
3724 	struct idr *idr_to_search;
3725 
3726 	resource = (struct drbd_resource *)cb->args[0];
3727 	if (!cb->args[0] && !cb->args[1]) {
3728 		resource_filter = find_cfg_context_attr(cb->nlh,
3729 				DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME);
3730 		if (resource_filter) {
3731 			retcode = ERR_RES_NOT_KNOWN;
3732 			resource = drbd_find_resource(nla_data(resource_filter));
3733 			if (!resource) {
3734 				rcu_read_lock();
3735 				goto put_result;
3736 			}
3737 		}
3738 		cb->args[0] = (long)resource;
3739 	}
3740 
3741 	rcu_read_lock();
3742 	minor = cb->args[1];
3743 	idr_to_search = resource ? &resource->devices : &drbd_devices;
3744 	device = idr_find(idr_to_search, minor);
3745 	if (!device) {
3746 next_device:
3747 		minor++;
3748 		cb->args[2] = 0;
3749 		device = idr_get_next(idr_to_search, &minor);
3750 		if (!device) {
3751 			err = 0;
3752 			goto out;
3753 		}
3754 	}
3755 	if (cb->args[2]) {
3756 		for_each_peer_device(peer_device, device)
3757 			if (peer_device == (struct drbd_peer_device *)cb->args[2])
3758 				goto found_peer_device;
3759 		/* peer device was probably deleted */
3760 		goto next_device;
3761 	}
3762 	/* Make peer_device point to the list head (not the first entry). */
3763 	peer_device = list_entry(&device->peer_devices, struct drbd_peer_device, peer_devices);
3764 
3765 found_peer_device:
3766 	list_for_each_entry_continue_rcu(peer_device, &device->peer_devices, peer_devices) {
3767 		if (!has_net_conf(peer_device->connection))
3768 			continue;
3769 		retcode = NO_ERROR;
3770 		goto put_result;  /* only one iteration */
3771 	}
3772 	goto next_device;
3773 
3774 put_result:
3775 	dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
3776 			cb->nlh->nlmsg_seq, &drbd_nl_family,
3777 			NLM_F_MULTI, DRBD_ADM_GET_PEER_DEVICES);
3778 	err = -ENOMEM;
3779 	if (!dh)
3780 		goto out;
3781 	dh->ret_code = retcode;
3782 	dh->minor = -1U;
3783 	if (retcode == NO_ERROR) {
3784 		struct peer_device_info peer_device_info;
3785 		struct peer_device_statistics peer_device_statistics;
3786 
3787 		dh->minor = minor;
3788 		err = nla_put_drbd_cfg_context(skb, device->resource, peer_device->connection, device);
3789 		if (err)
3790 			goto out;
3791 		peer_device_to_info(&peer_device_info, peer_device);
3792 		err = peer_device_info_to_skb(skb, &peer_device_info);
3793 		if (err)
3794 			goto out;
3795 		peer_device_to_statistics(&peer_device_statistics, peer_device);
3796 		err = peer_device_statistics_to_skb(skb, &peer_device_statistics);
3797 		if (err)
3798 			goto out;
3799 		cb->args[1] = minor;
3800 		cb->args[2] = (long)peer_device;
3801 	}
3802 	genlmsg_end(skb, dh);
3803 	err = 0;
3804 
3805 out:
3806 	rcu_read_unlock();
3807 	if (err)
3808 		return err;
3809 	return skb->len;
3810 }
3811 /*
3812  * Return the connection of @resource if @resource has exactly one connection.
3813  */
3814 static struct drbd_connection *the_only_connection(struct drbd_resource *resource)
3815 {
3816 	struct list_head *connections = &resource->connections;
3817 
3818 	if (list_empty(connections) || connections->next->next != connections)
3819 		return NULL;
3820 	return list_first_entry(&resource->connections, struct drbd_connection, connections);
3821 }
3822 
3823 static int nla_put_status_info(struct sk_buff *skb, struct drbd_device *device,
3824 		const struct sib_info *sib)
3825 {
3826 	struct drbd_resource *resource = device->resource;
3827 	struct state_info *si = NULL; /* for sizeof(si->member); */
3828 	struct nlattr *nla;
3829 	int got_ldev;
3830 	int err = 0;
3831 	int exclude_sensitive;
3832 
3833 	/* If sib != NULL, this is drbd_bcast_event, which anyone can listen
3834 	 * to.  So we better exclude_sensitive information.
3835 	 *
3836 	 * If sib == NULL, this is drbd_nl_get_status_doit, executed synchronously
3837 	 * in the context of the requesting user process. Exclude sensitive
3838 	 * information, unless current has superuser.
3839 	 *
3840 	 * NOTE: for drbd_nl_get_status_dumpit(), this is a netlink dump, and
3841 	 * relies on the current implementation of netlink_dump(), which
3842 	 * executes the dump callback successively from netlink_recvmsg(),
3843 	 * always in the context of the receiving process */
3844 	exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
3845 
3846 	got_ldev = get_ldev(device);
3847 
3848 	/* We need to add connection name and volume number information still.
3849 	 * Minor number is in drbd_genlmsghdr. */
3850 	if (nla_put_drbd_cfg_context(skb, resource, the_only_connection(resource), device))
3851 		goto nla_put_failure;
3852 
3853 	if (res_opts_to_skb(skb, &device->resource->res_opts))
3854 		goto nla_put_failure;
3855 
3856 	rcu_read_lock();
3857 	if (got_ldev) {
3858 		struct disk_conf *disk_conf;
3859 
3860 		disk_conf = rcu_dereference(device->ldev->disk_conf);
3861 		err = disk_conf_to_skb(skb, disk_conf);
3862 	}
3863 	if (!err) {
3864 		struct net_conf *nc;
3865 
3866 		nc = rcu_dereference(first_peer_device(device)->connection->net_conf);
3867 		if (nc)
3868 			err = net_conf_to_skb_sanitized(skb, nc, exclude_sensitive);
3869 	}
3870 	rcu_read_unlock();
3871 	if (err)
3872 		goto nla_put_failure;
3873 
3874 	nla = nla_nest_start_noflag(skb, DRBD_NLA_STATE_INFO);
3875 	if (!nla)
3876 		goto nla_put_failure;
3877 	if (nla_put_u32(skb, DRBD_A_STATE_INFO_SIB_REASON,
3878 		       sib ? sib->sib_reason : SIB_GET_STATUS_REPLY) ||
3879 	    nla_put_u32(skb, DRBD_A_STATE_INFO_CURRENT_STATE,
3880 		       device->state.i) ||
3881 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_ED_UUID,
3882 			     device->ed_uuid, 0) ||
3883 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_CAPACITY,
3884 			     get_capacity(device->vdisk), 0) ||
3885 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_SEND_CNT,
3886 			     device->send_cnt, 0) ||
3887 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_RECV_CNT,
3888 			     device->recv_cnt, 0) ||
3889 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_READ_CNT,
3890 			     device->read_cnt, 0) ||
3891 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_WRIT_CNT,
3892 			     device->writ_cnt, 0) ||
3893 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_AL_WRIT_CNT,
3894 			     device->al_writ_cnt, 0) ||
3895 	    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_BM_WRIT_CNT,
3896 			     device->bm_writ_cnt, 0) ||
3897 	    nla_put_u32(skb, DRBD_A_STATE_INFO_AP_BIO_CNT,
3898 		       atomic_read(&device->ap_bio_cnt)) ||
3899 	    nla_put_u32(skb, DRBD_A_STATE_INFO_AP_PENDING_CNT,
3900 		       atomic_read(&device->ap_pending_cnt)) ||
3901 	    nla_put_u32(skb, DRBD_A_STATE_INFO_RS_PENDING_CNT,
3902 		       atomic_read(&device->rs_pending_cnt)))
3903 		goto nla_put_failure;
3904 
3905 	if (got_ldev) {
3906 		int err;
3907 
3908 		spin_lock_irq(&device->ldev->md.uuid_lock);
3909 		err = nla_put(skb, DRBD_A_STATE_INFO_UUIDS,
3910 			     sizeof(si->uuids),
3911 			     device->ldev->md.uuid);
3912 		spin_unlock_irq(&device->ldev->md.uuid_lock);
3913 
3914 		if (err)
3915 			goto nla_put_failure;
3916 
3917 		if (nla_put_u32(skb, DRBD_A_STATE_INFO_DISK_FLAGS, device->ldev->md.flags) ||
3918 		    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_BITS_TOTAL, drbd_bm_bits(device), 0) ||
3919 		    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_BITS_OOS,
3920 				      drbd_bm_total_weight(device), 0))
3921 			goto nla_put_failure;
3922 		if (C_SYNC_SOURCE <= device->state.conn &&
3923 		    C_PAUSED_SYNC_T >= device->state.conn) {
3924 			if (nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_BITS_RS_TOTAL,
3925 					      device->rs_total, 0) ||
3926 			    nla_put_u64_64bit(skb, DRBD_A_STATE_INFO_BITS_RS_FAILED,
3927 					      device->rs_failed, 0))
3928 				goto nla_put_failure;
3929 		}
3930 	}
3931 
3932 	if (sib) {
3933 		switch(sib->sib_reason) {
3934 		case SIB_SYNC_PROGRESS:
3935 		case SIB_GET_STATUS_REPLY:
3936 			break;
3937 		case SIB_STATE_CHANGE:
3938 			if (nla_put_u32(skb, DRBD_A_STATE_INFO_PREV_STATE, sib->os.i) ||
3939 			    nla_put_u32(skb, DRBD_A_STATE_INFO_NEW_STATE, sib->ns.i))
3940 				goto nla_put_failure;
3941 			break;
3942 		case SIB_HELPER_POST:
3943 			if (nla_put_u32(skb, DRBD_A_STATE_INFO_HELPER_EXIT_CODE,
3944 					sib->helper_exit_code))
3945 				goto nla_put_failure;
3946 			fallthrough;
3947 		case SIB_HELPER_PRE:
3948 			if (nla_put_string(skb, DRBD_A_STATE_INFO_HELPER, sib->helper_name))
3949 				goto nla_put_failure;
3950 			break;
3951 		}
3952 	}
3953 	nla_nest_end(skb, nla);
3954 
3955 	if (0)
3956 nla_put_failure:
3957 		err = -EMSGSIZE;
3958 	if (got_ldev)
3959 		put_ldev(device);
3960 	return err;
3961 }
3962 
3963 int drbd_nl_get_status_doit(struct sk_buff *skb, struct genl_info *info)
3964 {
3965 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
3966 	enum drbd_ret_code retcode;
3967 	int err;
3968 
3969 	if (!adm_ctx->reply_skb)
3970 		return 0;
3971 	retcode = adm_ctx->reply_dh->ret_code;
3972 	if (retcode != NO_ERROR)
3973 		goto out;
3974 
3975 	err = nla_put_status_info(adm_ctx->reply_skb, adm_ctx->device, NULL);
3976 	if (err) {
3977 		nlmsg_free(adm_ctx->reply_skb);
3978 		adm_ctx->reply_skb = NULL;
3979 		return err;
3980 	}
3981 out:
3982 	adm_ctx->reply_dh->ret_code = retcode;
3983 	return 0;
3984 }
3985 
3986 static int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
3987 {
3988 	struct drbd_device *device;
3989 	struct drbd_genlmsghdr *dh;
3990 	struct drbd_resource *pos = (struct drbd_resource *)cb->args[0];
3991 	struct drbd_resource *resource = NULL;
3992 	struct drbd_resource *tmp;
3993 	unsigned volume = cb->args[1];
3994 
3995 	/* Open coded, deferred, iteration:
3996 	 * for_each_resource_safe(resource, tmp, &drbd_resources) {
3997 	 *      connection = "first connection of resource or undefined";
3998 	 *	idr_for_each_entry(&resource->devices, device, i) {
3999 	 *	  ...
4000 	 *	}
4001 	 * }
4002 	 * where resource is cb->args[0];
4003 	 * and i is cb->args[1];
4004 	 *
4005 	 * cb->args[2] indicates if we shall loop over all resources,
4006 	 * or just dump all volumes of a single resource.
4007 	 *
4008 	 * This may miss entries inserted after this dump started,
4009 	 * or entries deleted before they are reached.
4010 	 *
4011 	 * We need to make sure the device won't disappear while
4012 	 * we are looking at it, and revalidate our iterators
4013 	 * on each iteration.
4014 	 */
4015 
4016 	/* synchronize with conn_create()/drbd_destroy_connection() */
4017 	rcu_read_lock();
4018 	/* revalidate iterator position */
4019 	for_each_resource_rcu(tmp, &drbd_resources) {
4020 		if (pos == NULL) {
4021 			/* first iteration */
4022 			pos = tmp;
4023 			resource = pos;
4024 			break;
4025 		}
4026 		if (tmp == pos) {
4027 			resource = pos;
4028 			break;
4029 		}
4030 	}
4031 	if (resource) {
4032 next_resource:
4033 		device = idr_get_next(&resource->devices, &volume);
4034 		if (!device) {
4035 			/* No more volumes to dump on this resource.
4036 			 * Advance resource iterator. */
4037 			pos = list_entry_rcu(resource->resources.next,
4038 					     struct drbd_resource, resources);
4039 			/* Did we dump any volume of this resource yet? */
4040 			if (volume != 0) {
4041 				/* If we reached the end of the list,
4042 				 * or only a single resource dump was requested,
4043 				 * we are done. */
4044 				if (&pos->resources == &drbd_resources || cb->args[2])
4045 					goto out;
4046 				volume = 0;
4047 				resource = pos;
4048 				goto next_resource;
4049 			}
4050 		}
4051 
4052 		dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
4053 				cb->nlh->nlmsg_seq, &drbd_nl_family,
4054 				NLM_F_MULTI, DRBD_ADM_GET_STATUS);
4055 		if (!dh)
4056 			goto out;
4057 
4058 		if (!device) {
4059 			/* This is a connection without a single volume.
4060 			 * Suprisingly enough, it may have a network
4061 			 * configuration. */
4062 			struct drbd_connection *connection;
4063 
4064 			dh->minor = -1U;
4065 			dh->ret_code = NO_ERROR;
4066 			connection = the_only_connection(resource);
4067 			if (nla_put_drbd_cfg_context(skb, resource, connection, NULL))
4068 				goto cancel;
4069 			if (connection) {
4070 				struct net_conf *nc;
4071 
4072 				nc = rcu_dereference(connection->net_conf);
4073 				if (nc && net_conf_to_skb_sanitized(skb, nc, true) != 0)
4074 					goto cancel;
4075 			}
4076 			goto done;
4077 		}
4078 
4079 		D_ASSERT(device, device->vnr == volume);
4080 		D_ASSERT(device, device->resource == resource);
4081 
4082 		dh->minor = device_to_minor(device);
4083 		dh->ret_code = NO_ERROR;
4084 
4085 		if (nla_put_status_info(skb, device, NULL)) {
4086 cancel:
4087 			genlmsg_cancel(skb, dh);
4088 			goto out;
4089 		}
4090 done:
4091 		genlmsg_end(skb, dh);
4092 	}
4093 
4094 out:
4095 	rcu_read_unlock();
4096 	/* where to start the next iteration */
4097 	cb->args[0] = (long)pos;
4098 	cb->args[1] = (pos == resource) ? volume + 1 : 0;
4099 
4100 	/* No more resources/volumes/minors found results in an empty skb.
4101 	 * Which will terminate the dump. */
4102         return skb->len;
4103 }
4104 
4105 /*
4106  * Request status of all resources, or of all volumes within a single resource.
4107  *
4108  * This is a dump, as the answer may not fit in a single reply skb otherwise.
4109  * Which means we cannot use the family->attrbuf or other such members, because
4110  * dump is NOT protected by the genl_lock().  During dump, we only have access
4111  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
4112  *
4113  * Once things are setup properly, we call into get_one_status().
4114  */
4115 int drbd_nl_get_status_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
4116 {
4117 	const unsigned int hdrlen = GENL_HDRLEN + sizeof(struct drbd_genlmsghdr);
4118 	struct nlattr *nla;
4119 	const char *resource_name;
4120 	struct drbd_resource *resource;
4121 
4122 	/* Is this a followup call? */
4123 	if (cb->args[0]) {
4124 		/* ... of a single resource dump,
4125 		 * and the resource iterator has been advanced already? */
4126 		if (cb->args[2] && cb->args[2] != cb->args[0])
4127 			return 0; /* DONE. */
4128 		goto dump;
4129 	}
4130 
4131 	/* First call (from netlink_dump_start).  We need to figure out
4132 	 * which resource(s) the user wants us to dump. */
4133 	nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
4134 			nlmsg_attrlen(cb->nlh, hdrlen),
4135 			DRBD_NLA_CFG_CONTEXT);
4136 
4137 	/* No explicit context given.  Dump all. */
4138 	if (!nla)
4139 		goto dump;
4140 	nla = nla_find_nested(nla, DRBD_A_DRBD_CFG_CONTEXT_CTX_RESOURCE_NAME);
4141 	/* context given, but no name present? */
4142 	if (!nla)
4143 		return -EINVAL;
4144 	resource_name = nla_data(nla);
4145 	if (!*resource_name)
4146 		return -ENODEV;
4147 	resource = drbd_find_resource(resource_name);
4148 	if (!resource)
4149 		return -ENODEV;
4150 
4151 	kref_put(&resource->kref, drbd_destroy_resource); /* get_one_status() revalidates the resource */
4152 
4153 	/* prime iterators, and set "filter" mode mark:
4154 	 * only dump this connection. */
4155 	cb->args[0] = (long)resource;
4156 	/* cb->args[1] = 0; passed in this way. */
4157 	cb->args[2] = (long)resource;
4158 
4159 dump:
4160 	return get_one_status(skb, cb);
4161 }
4162 
4163 int drbd_nl_get_timeout_type_doit(struct sk_buff *skb, struct genl_info *info)
4164 {
4165 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4166 	enum drbd_ret_code retcode;
4167 	struct timeout_parms tp;
4168 	int err;
4169 
4170 	if (!adm_ctx->reply_skb)
4171 		return 0;
4172 	retcode = adm_ctx->reply_dh->ret_code;
4173 	if (retcode != NO_ERROR)
4174 		goto out;
4175 
4176 	tp.timeout_type =
4177 		adm_ctx->device->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
4178 		test_bit(USE_DEGR_WFC_T, &adm_ctx->device->flags) ? UT_DEGRADED :
4179 		UT_DEFAULT;
4180 
4181 	err = timeout_parms_to_skb(adm_ctx->reply_skb, &tp);
4182 	if (err) {
4183 		nlmsg_free(adm_ctx->reply_skb);
4184 		adm_ctx->reply_skb = NULL;
4185 		return err;
4186 	}
4187 out:
4188 	adm_ctx->reply_dh->ret_code = retcode;
4189 	return 0;
4190 }
4191 
4192 int drbd_nl_start_ov_doit(struct sk_buff *skb, struct genl_info *info)
4193 {
4194 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4195 	struct drbd_device *device;
4196 	enum drbd_ret_code retcode;
4197 	struct start_ov_parms parms;
4198 
4199 	if (!adm_ctx->reply_skb)
4200 		return 0;
4201 	retcode = adm_ctx->reply_dh->ret_code;
4202 	if (retcode != NO_ERROR)
4203 		goto out;
4204 
4205 	device = adm_ctx->device;
4206 
4207 	/* resume from last known position, if possible */
4208 	parms.ov_start_sector = device->ov_start_sector;
4209 	parms.ov_stop_sector = ULLONG_MAX;
4210 	if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
4211 		int err = start_ov_parms_from_attrs(&parms, info);
4212 		if (err) {
4213 			retcode = ERR_MANDATORY_TAG;
4214 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
4215 			goto out;
4216 		}
4217 	}
4218 	mutex_lock(&adm_ctx->resource->adm_mutex);
4219 
4220 	/* w_make_ov_request expects position to be aligned */
4221 	device->ov_start_sector = parms.ov_start_sector & ~(BM_SECT_PER_BIT-1);
4222 	device->ov_stop_sector = parms.ov_stop_sector;
4223 
4224 	/* If there is still bitmap IO pending, e.g. previous resync or verify
4225 	 * just being finished, wait for it before requesting a new resync. */
4226 	drbd_suspend_io(device);
4227 	wait_event(device->misc_wait, !test_bit(BITMAP_IO, &device->flags));
4228 	retcode = drbd_request_state(device, NS(conn, C_VERIFY_S));
4229 	drbd_resume_io(device);
4230 
4231 	mutex_unlock(&adm_ctx->resource->adm_mutex);
4232 out:
4233 	adm_ctx->reply_dh->ret_code = retcode;
4234 	return 0;
4235 }
4236 
4237 
4238 int drbd_nl_new_c_uuid_doit(struct sk_buff *skb, struct genl_info *info)
4239 {
4240 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4241 	struct drbd_device *device;
4242 	enum drbd_ret_code retcode;
4243 	int skip_initial_sync = 0;
4244 	int err;
4245 	struct new_c_uuid_parms args;
4246 
4247 	if (!adm_ctx->reply_skb)
4248 		return 0;
4249 	retcode = adm_ctx->reply_dh->ret_code;
4250 	if (retcode != NO_ERROR)
4251 		goto out_nolock;
4252 
4253 	device = adm_ctx->device;
4254 	memset(&args, 0, sizeof(args));
4255 	if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
4256 		err = new_c_uuid_parms_from_attrs(&args, info);
4257 		if (err) {
4258 			retcode = ERR_MANDATORY_TAG;
4259 			drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
4260 			goto out_nolock;
4261 		}
4262 	}
4263 
4264 	mutex_lock(&adm_ctx->resource->adm_mutex);
4265 	mutex_lock(device->state_mutex); /* Protects us against serialized state changes. */
4266 
4267 	if (!get_ldev(device)) {
4268 		retcode = ERR_NO_DISK;
4269 		goto out;
4270 	}
4271 
4272 	/* this is "skip initial sync", assume to be clean */
4273 	if (device->state.conn == C_CONNECTED &&
4274 	    first_peer_device(device)->connection->agreed_pro_version >= 90 &&
4275 	    device->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
4276 		drbd_info(device, "Preparing to skip initial sync\n");
4277 		skip_initial_sync = 1;
4278 	} else if (device->state.conn != C_STANDALONE) {
4279 		retcode = ERR_CONNECTED;
4280 		goto out_dec;
4281 	}
4282 
4283 	drbd_uuid_set(device, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
4284 	drbd_uuid_new_current(device); /* New current, previous to UI_BITMAP */
4285 
4286 	if (args.clear_bm) {
4287 		err = drbd_bitmap_io(device, &drbd_bmio_clear_n_write,
4288 			"clear_n_write from new_c_uuid", BM_LOCKED_MASK, NULL);
4289 		if (err) {
4290 			drbd_err(device, "Writing bitmap failed with %d\n", err);
4291 			retcode = ERR_IO_MD_DISK;
4292 		}
4293 		if (skip_initial_sync) {
4294 			drbd_send_uuids_skip_initial_sync(first_peer_device(device));
4295 			_drbd_uuid_set(device, UI_BITMAP, 0);
4296 			drbd_print_uuids(device, "cleared bitmap UUID");
4297 			spin_lock_irq(&device->resource->req_lock);
4298 			_drbd_set_state(_NS2(device, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
4299 					CS_VERBOSE, NULL);
4300 			spin_unlock_irq(&device->resource->req_lock);
4301 		}
4302 	}
4303 
4304 	drbd_md_sync(device);
4305 out_dec:
4306 	put_ldev(device);
4307 out:
4308 	mutex_unlock(device->state_mutex);
4309 	mutex_unlock(&adm_ctx->resource->adm_mutex);
4310 out_nolock:
4311 	adm_ctx->reply_dh->ret_code = retcode;
4312 	return 0;
4313 }
4314 
4315 static enum drbd_ret_code
4316 drbd_check_resource_name(struct drbd_config_context *adm_ctx)
4317 {
4318 	const char *name = adm_ctx->resource_name;
4319 	if (!name || !name[0]) {
4320 		drbd_msg_put_info(adm_ctx->reply_skb, "resource name missing");
4321 		return ERR_MANDATORY_TAG;
4322 	}
4323 	/* if we want to use these in sysfs/configfs/debugfs some day,
4324 	 * we must not allow slashes */
4325 	if (strchr(name, '/')) {
4326 		drbd_msg_put_info(adm_ctx->reply_skb, "invalid resource name");
4327 		return ERR_INVALID_REQUEST;
4328 	}
4329 	return NO_ERROR;
4330 }
4331 
4332 static void resource_to_info(struct resource_info *info,
4333 			     struct drbd_resource *resource)
4334 {
4335 	info->res_role = conn_highest_role(first_connection(resource));
4336 	info->res_susp = resource->susp;
4337 	info->res_susp_nod = resource->susp_nod;
4338 	info->res_susp_fen = resource->susp_fen;
4339 }
4340 
4341 int drbd_nl_new_resource_doit(struct sk_buff *skb, struct genl_info *info)
4342 {
4343 	struct drbd_connection *connection;
4344 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4345 	enum drbd_ret_code retcode;
4346 	struct res_opts res_opts;
4347 	int err;
4348 
4349 	if (!adm_ctx->reply_skb)
4350 		return 0;
4351 	retcode = adm_ctx->reply_dh->ret_code;
4352 	if (retcode != NO_ERROR)
4353 		goto out;
4354 
4355 	set_res_opts_defaults(&res_opts);
4356 	err = res_opts_from_attrs(&res_opts, info);
4357 	if (err && err != -ENOMSG) {
4358 		retcode = ERR_MANDATORY_TAG;
4359 		drbd_msg_put_info(adm_ctx->reply_skb, from_attrs_err_to_txt(err));
4360 		goto out;
4361 	}
4362 
4363 	retcode = drbd_check_resource_name(adm_ctx);
4364 	if (retcode != NO_ERROR)
4365 		goto out;
4366 
4367 	if (adm_ctx->resource) {
4368 		if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
4369 			retcode = ERR_INVALID_REQUEST;
4370 			drbd_msg_put_info(adm_ctx->reply_skb, "resource exists");
4371 		}
4372 		/* else: still NO_ERROR */
4373 		goto out;
4374 	}
4375 
4376 	/* not yet safe for genl_family.parallel_ops */
4377 	mutex_lock(&resources_mutex);
4378 	connection = conn_create(adm_ctx->resource_name, &res_opts);
4379 	mutex_unlock(&resources_mutex);
4380 
4381 	if (connection) {
4382 		struct resource_info resource_info;
4383 
4384 		mutex_lock(&notification_mutex);
4385 		resource_to_info(&resource_info, connection->resource);
4386 		notify_resource_state(NULL, 0, connection->resource,
4387 				      &resource_info, NOTIFY_CREATE);
4388 		mutex_unlock(&notification_mutex);
4389 	} else
4390 		retcode = ERR_NOMEM;
4391 
4392 out:
4393 	adm_ctx->reply_dh->ret_code = retcode;
4394 	return 0;
4395 }
4396 
4397 static void device_to_info(struct device_info *info,
4398 			   struct drbd_device *device)
4399 {
4400 	info->dev_disk_state = device->state.disk;
4401 }
4402 
4403 
4404 int drbd_nl_new_minor_doit(struct sk_buff *skb, struct genl_info *info)
4405 {
4406 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4407 	struct drbd_genlmsghdr *dh = genl_info_userhdr(info);
4408 	enum drbd_ret_code retcode;
4409 
4410 	if (!adm_ctx->reply_skb)
4411 		return 0;
4412 	retcode = adm_ctx->reply_dh->ret_code;
4413 	if (retcode != NO_ERROR)
4414 		goto out;
4415 
4416 	if (dh->minor > MINORMASK) {
4417 		drbd_msg_put_info(adm_ctx->reply_skb, "requested minor out of range");
4418 		retcode = ERR_INVALID_REQUEST;
4419 		goto out;
4420 	}
4421 	if (adm_ctx->volume > DRBD_VOLUME_MAX) {
4422 		drbd_msg_put_info(adm_ctx->reply_skb, "requested volume id out of range");
4423 		retcode = ERR_INVALID_REQUEST;
4424 		goto out;
4425 	}
4426 
4427 	/* drbd_adm_prepare made sure already
4428 	 * that first_peer_device(device)->connection and device->vnr match the request. */
4429 	if (adm_ctx->device) {
4430 		if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
4431 			retcode = ERR_MINOR_OR_VOLUME_EXISTS;
4432 		/* else: still NO_ERROR */
4433 		goto out;
4434 	}
4435 
4436 	mutex_lock(&adm_ctx->resource->adm_mutex);
4437 	retcode = drbd_create_device(adm_ctx, dh->minor);
4438 	if (retcode == NO_ERROR) {
4439 		struct drbd_device *device;
4440 		struct drbd_peer_device *peer_device;
4441 		struct device_info info;
4442 		unsigned int peer_devices = 0;
4443 		enum drbd_notification_type flags;
4444 
4445 		device = minor_to_device(dh->minor);
4446 		for_each_peer_device(peer_device, device) {
4447 			if (!has_net_conf(peer_device->connection))
4448 				continue;
4449 			peer_devices++;
4450 		}
4451 
4452 		device_to_info(&info, device);
4453 		mutex_lock(&notification_mutex);
4454 		flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
4455 		notify_device_state(NULL, 0, device, &info, NOTIFY_CREATE | flags);
4456 		for_each_peer_device(peer_device, device) {
4457 			struct peer_device_info peer_device_info;
4458 
4459 			if (!has_net_conf(peer_device->connection))
4460 				continue;
4461 			peer_device_to_info(&peer_device_info, peer_device);
4462 			flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
4463 			notify_peer_device_state(NULL, 0, peer_device, &peer_device_info,
4464 						 NOTIFY_CREATE | flags);
4465 		}
4466 		mutex_unlock(&notification_mutex);
4467 	}
4468 	mutex_unlock(&adm_ctx->resource->adm_mutex);
4469 out:
4470 	adm_ctx->reply_dh->ret_code = retcode;
4471 	return 0;
4472 }
4473 
4474 static enum drbd_ret_code adm_del_minor(struct drbd_device *device)
4475 {
4476 	struct drbd_peer_device *peer_device;
4477 
4478 	if (device->state.disk == D_DISKLESS &&
4479 	    /* no need to be device->state.conn == C_STANDALONE &&
4480 	     * we may want to delete a minor from a live replication group.
4481 	     */
4482 	    device->state.role == R_SECONDARY) {
4483 		struct drbd_connection *connection =
4484 			first_connection(device->resource);
4485 
4486 		_drbd_request_state(device, NS(conn, C_WF_REPORT_PARAMS),
4487 				    CS_VERBOSE + CS_WAIT_COMPLETE);
4488 
4489 		/* If the state engine hasn't stopped the sender thread yet, we
4490 		 * need to flush the sender work queue before generating the
4491 		 * DESTROY events here. */
4492 		if (get_t_state(&connection->worker) == RUNNING)
4493 			drbd_flush_workqueue(&connection->sender_work);
4494 
4495 		mutex_lock(&notification_mutex);
4496 		for_each_peer_device(peer_device, device) {
4497 			if (!has_net_conf(peer_device->connection))
4498 				continue;
4499 			notify_peer_device_state(NULL, 0, peer_device, NULL,
4500 						 NOTIFY_DESTROY | NOTIFY_CONTINUES);
4501 		}
4502 		notify_device_state(NULL, 0, device, NULL, NOTIFY_DESTROY);
4503 		mutex_unlock(&notification_mutex);
4504 
4505 		drbd_delete_device(device);
4506 		return NO_ERROR;
4507 	} else
4508 		return ERR_MINOR_CONFIGURED;
4509 }
4510 
4511 int drbd_nl_del_minor_doit(struct sk_buff *skb, struct genl_info *info)
4512 {
4513 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4514 	enum drbd_ret_code retcode;
4515 
4516 	if (!adm_ctx->reply_skb)
4517 		return 0;
4518 	retcode = adm_ctx->reply_dh->ret_code;
4519 	if (retcode != NO_ERROR)
4520 		goto out;
4521 
4522 	mutex_lock(&adm_ctx->resource->adm_mutex);
4523 	retcode = adm_del_minor(adm_ctx->device);
4524 	mutex_unlock(&adm_ctx->resource->adm_mutex);
4525 out:
4526 	adm_ctx->reply_dh->ret_code = retcode;
4527 	return 0;
4528 }
4529 
4530 static int adm_del_resource(struct drbd_resource *resource)
4531 {
4532 	struct drbd_connection *connection;
4533 
4534 	for_each_connection(connection, resource) {
4535 		if (connection->cstate > C_STANDALONE)
4536 			return ERR_NET_CONFIGURED;
4537 	}
4538 	if (!idr_is_empty(&resource->devices))
4539 		return ERR_RES_IN_USE;
4540 
4541 	/* The state engine has stopped the sender thread, so we don't
4542 	 * need to flush the sender work queue before generating the
4543 	 * DESTROY event here. */
4544 	mutex_lock(&notification_mutex);
4545 	notify_resource_state(NULL, 0, resource, NULL, NOTIFY_DESTROY);
4546 	mutex_unlock(&notification_mutex);
4547 
4548 	mutex_lock(&resources_mutex);
4549 	list_del_rcu(&resource->resources);
4550 	mutex_unlock(&resources_mutex);
4551 	/* Make sure all threads have actually stopped: state handling only
4552 	 * does drbd_thread_stop_nowait(). */
4553 	list_for_each_entry(connection, &resource->connections, connections)
4554 		drbd_thread_stop(&connection->worker);
4555 	synchronize_rcu();
4556 	drbd_free_resource(resource);
4557 	return NO_ERROR;
4558 }
4559 
4560 int drbd_nl_down_doit(struct sk_buff *skb, struct genl_info *info)
4561 {
4562 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4563 	struct drbd_resource *resource;
4564 	struct drbd_connection *connection;
4565 	struct drbd_device *device;
4566 	int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
4567 	unsigned i;
4568 
4569 	if (!adm_ctx->reply_skb)
4570 		return 0;
4571 	retcode = adm_ctx->reply_dh->ret_code;
4572 	if (retcode != NO_ERROR)
4573 		goto finish;
4574 
4575 	resource = adm_ctx->resource;
4576 	mutex_lock(&resource->adm_mutex);
4577 	/* demote */
4578 	for_each_connection(connection, resource) {
4579 		struct drbd_peer_device *peer_device;
4580 
4581 		idr_for_each_entry(&connection->peer_devices, peer_device, i) {
4582 			retcode = drbd_set_role(peer_device->device, R_SECONDARY, 0);
4583 			if (retcode < SS_SUCCESS) {
4584 				drbd_msg_put_info(adm_ctx->reply_skb, "failed to demote");
4585 				goto out;
4586 			}
4587 		}
4588 
4589 		retcode = conn_try_disconnect(connection, 0);
4590 		if (retcode < SS_SUCCESS) {
4591 			drbd_msg_put_info(adm_ctx->reply_skb, "failed to disconnect");
4592 			goto out;
4593 		}
4594 	}
4595 
4596 	/* detach */
4597 	idr_for_each_entry(&resource->devices, device, i) {
4598 		retcode = adm_detach(device, 0);
4599 		if (retcode < SS_SUCCESS || retcode > NO_ERROR) {
4600 			drbd_msg_put_info(adm_ctx->reply_skb, "failed to detach");
4601 			goto out;
4602 		}
4603 	}
4604 
4605 	/* delete volumes */
4606 	idr_for_each_entry(&resource->devices, device, i) {
4607 		retcode = adm_del_minor(device);
4608 		if (retcode != NO_ERROR) {
4609 			/* "can not happen" */
4610 			drbd_msg_put_info(adm_ctx->reply_skb, "failed to delete volume");
4611 			goto out;
4612 		}
4613 	}
4614 
4615 	retcode = adm_del_resource(resource);
4616 out:
4617 	mutex_unlock(&resource->adm_mutex);
4618 finish:
4619 	adm_ctx->reply_dh->ret_code = retcode;
4620 	return 0;
4621 }
4622 
4623 int drbd_nl_del_resource_doit(struct sk_buff *skb, struct genl_info *info)
4624 {
4625 	struct drbd_config_context *adm_ctx = info->user_ptr[0];
4626 	struct drbd_resource *resource;
4627 	enum drbd_ret_code retcode;
4628 
4629 	if (!adm_ctx->reply_skb)
4630 		return 0;
4631 	retcode = adm_ctx->reply_dh->ret_code;
4632 	if (retcode != NO_ERROR)
4633 		goto finish;
4634 	resource = adm_ctx->resource;
4635 
4636 	mutex_lock(&resource->adm_mutex);
4637 	retcode = adm_del_resource(resource);
4638 	mutex_unlock(&resource->adm_mutex);
4639 finish:
4640 	adm_ctx->reply_dh->ret_code = retcode;
4641 	return 0;
4642 }
4643 
4644 void drbd_bcast_event(struct drbd_device *device, const struct sib_info *sib)
4645 {
4646 	struct sk_buff *msg;
4647 	struct drbd_genlmsghdr *d_out;
4648 	unsigned seq;
4649 	int err = -ENOMEM;
4650 
4651 	seq = atomic_inc_return(&drbd_genl_seq);
4652 	msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4653 	if (!msg)
4654 		goto failed;
4655 
4656 	err = -EMSGSIZE;
4657 	d_out = genlmsg_put(msg, 0, seq, &drbd_nl_family, 0, DRBD_ADM_EVENT);
4658 	if (!d_out) /* cannot happen, but anyways. */
4659 		goto nla_put_failure;
4660 	d_out->minor = device_to_minor(device);
4661 	d_out->ret_code = NO_ERROR;
4662 
4663 	if (nla_put_status_info(msg, device, sib))
4664 		goto nla_put_failure;
4665 	genlmsg_end(msg, d_out);
4666 	err = drbd_genl_multicast_events(msg, GFP_NOWAIT);
4667 	/* msg has been consumed or freed in netlink_broadcast() */
4668 	if (err && err != -ESRCH)
4669 		goto failed;
4670 
4671 	return;
4672 
4673 nla_put_failure:
4674 	nlmsg_free(msg);
4675 failed:
4676 	drbd_err(device, "Error %d while broadcasting event. "
4677 			"Event seq:%u sib_reason:%u\n",
4678 			err, seq, sib->sib_reason);
4679 }
4680 
4681 static int nla_put_notification_header(struct sk_buff *msg,
4682 				       enum drbd_notification_type type)
4683 {
4684 	struct drbd_notification_header nh = {
4685 		.nh_type = type,
4686 	};
4687 
4688 	return drbd_notification_header_to_skb(msg, &nh);
4689 }
4690 
4691 int notify_resource_state(struct sk_buff *skb,
4692 			   unsigned int seq,
4693 			   struct drbd_resource *resource,
4694 			   struct resource_info *resource_info,
4695 			   enum drbd_notification_type type)
4696 {
4697 	struct resource_statistics resource_statistics;
4698 	struct drbd_genlmsghdr *dh;
4699 	bool multicast = false;
4700 	int err;
4701 
4702 	if (!skb) {
4703 		seq = atomic_inc_return(&notify_genl_seq);
4704 		skb = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4705 		err = -ENOMEM;
4706 		if (!skb)
4707 			goto failed;
4708 		multicast = true;
4709 	}
4710 
4711 	err = -EMSGSIZE;
4712 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_RESOURCE_STATE);
4713 	if (!dh)
4714 		goto nla_put_failure;
4715 	dh->minor = -1U;
4716 	dh->ret_code = NO_ERROR;
4717 	if (nla_put_drbd_cfg_context(skb, resource, NULL, NULL) ||
4718 	    nla_put_notification_header(skb, type) ||
4719 	    ((type & ~NOTIFY_FLAGS) != NOTIFY_DESTROY &&
4720 	     resource_info_to_skb(skb, resource_info)))
4721 		goto nla_put_failure;
4722 	resource_statistics.res_stat_write_ordering = resource->write_ordering;
4723 	err = resource_statistics_to_skb(skb, &resource_statistics);
4724 	if (err)
4725 		goto nla_put_failure;
4726 	genlmsg_end(skb, dh);
4727 	if (multicast) {
4728 		err = drbd_genl_multicast_events(skb, GFP_NOWAIT);
4729 		/* skb has been consumed or freed in netlink_broadcast() */
4730 		if (err && err != -ESRCH)
4731 			goto failed;
4732 	}
4733 	return 0;
4734 
4735 nla_put_failure:
4736 	nlmsg_free(skb);
4737 failed:
4738 	drbd_err(resource, "Error %d while broadcasting event. Event seq:%u\n",
4739 			err, seq);
4740 	return err;
4741 }
4742 
4743 int notify_device_state(struct sk_buff *skb,
4744 			 unsigned int seq,
4745 			 struct drbd_device *device,
4746 			 struct device_info *device_info,
4747 			 enum drbd_notification_type type)
4748 {
4749 	struct device_statistics device_statistics;
4750 	struct drbd_genlmsghdr *dh;
4751 	bool multicast = false;
4752 	int err;
4753 
4754 	if (!skb) {
4755 		seq = atomic_inc_return(&notify_genl_seq);
4756 		skb = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4757 		err = -ENOMEM;
4758 		if (!skb)
4759 			goto failed;
4760 		multicast = true;
4761 	}
4762 
4763 	err = -EMSGSIZE;
4764 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_DEVICE_STATE);
4765 	if (!dh)
4766 		goto nla_put_failure;
4767 	dh->minor = device->minor;
4768 	dh->ret_code = NO_ERROR;
4769 	if (nla_put_drbd_cfg_context(skb, device->resource, NULL, device) ||
4770 	    nla_put_notification_header(skb, type) ||
4771 	    ((type & ~NOTIFY_FLAGS) != NOTIFY_DESTROY &&
4772 	     device_info_to_skb(skb, device_info)))
4773 		goto nla_put_failure;
4774 	device_to_statistics(&device_statistics, device);
4775 	device_statistics_to_skb(skb, &device_statistics);
4776 	genlmsg_end(skb, dh);
4777 	if (multicast) {
4778 		err = drbd_genl_multicast_events(skb, GFP_NOWAIT);
4779 		/* skb has been consumed or freed in netlink_broadcast() */
4780 		if (err && err != -ESRCH)
4781 			goto failed;
4782 	}
4783 	return 0;
4784 
4785 nla_put_failure:
4786 	nlmsg_free(skb);
4787 failed:
4788 	drbd_err(device, "Error %d while broadcasting event. Event seq:%u\n",
4789 		 err, seq);
4790 	return err;
4791 }
4792 
4793 int notify_connection_state(struct sk_buff *skb,
4794 			     unsigned int seq,
4795 			     struct drbd_connection *connection,
4796 			     struct connection_info *connection_info,
4797 			     enum drbd_notification_type type)
4798 {
4799 	struct connection_statistics connection_statistics;
4800 	struct drbd_genlmsghdr *dh;
4801 	bool multicast = false;
4802 	int err;
4803 
4804 	if (!skb) {
4805 		seq = atomic_inc_return(&notify_genl_seq);
4806 		skb = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4807 		err = -ENOMEM;
4808 		if (!skb)
4809 			goto failed;
4810 		multicast = true;
4811 	}
4812 
4813 	err = -EMSGSIZE;
4814 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_CONNECTION_STATE);
4815 	if (!dh)
4816 		goto nla_put_failure;
4817 	dh->minor = -1U;
4818 	dh->ret_code = NO_ERROR;
4819 	if (nla_put_drbd_cfg_context(skb, connection->resource, connection, NULL) ||
4820 	    nla_put_notification_header(skb, type) ||
4821 	    ((type & ~NOTIFY_FLAGS) != NOTIFY_DESTROY &&
4822 	     connection_info_to_skb(skb, connection_info)))
4823 		goto nla_put_failure;
4824 	connection_statistics.conn_congested = test_bit(NET_CONGESTED, &connection->flags);
4825 	connection_statistics_to_skb(skb, &connection_statistics);
4826 	genlmsg_end(skb, dh);
4827 	if (multicast) {
4828 		err = drbd_genl_multicast_events(skb, GFP_NOWAIT);
4829 		/* skb has been consumed or freed in netlink_broadcast() */
4830 		if (err && err != -ESRCH)
4831 			goto failed;
4832 	}
4833 	return 0;
4834 
4835 nla_put_failure:
4836 	nlmsg_free(skb);
4837 failed:
4838 	drbd_err(connection, "Error %d while broadcasting event. Event seq:%u\n",
4839 		 err, seq);
4840 	return err;
4841 }
4842 
4843 int notify_peer_device_state(struct sk_buff *skb,
4844 			      unsigned int seq,
4845 			      struct drbd_peer_device *peer_device,
4846 			      struct peer_device_info *peer_device_info,
4847 			      enum drbd_notification_type type)
4848 {
4849 	struct peer_device_statistics peer_device_statistics;
4850 	struct drbd_resource *resource = peer_device->device->resource;
4851 	struct drbd_genlmsghdr *dh;
4852 	bool multicast = false;
4853 	int err;
4854 
4855 	if (!skb) {
4856 		seq = atomic_inc_return(&notify_genl_seq);
4857 		skb = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4858 		err = -ENOMEM;
4859 		if (!skb)
4860 			goto failed;
4861 		multicast = true;
4862 	}
4863 
4864 	err = -EMSGSIZE;
4865 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_PEER_DEVICE_STATE);
4866 	if (!dh)
4867 		goto nla_put_failure;
4868 	dh->minor = -1U;
4869 	dh->ret_code = NO_ERROR;
4870 	if (nla_put_drbd_cfg_context(skb, resource, peer_device->connection, peer_device->device) ||
4871 	    nla_put_notification_header(skb, type) ||
4872 	    ((type & ~NOTIFY_FLAGS) != NOTIFY_DESTROY &&
4873 	     peer_device_info_to_skb(skb, peer_device_info)))
4874 		goto nla_put_failure;
4875 	peer_device_to_statistics(&peer_device_statistics, peer_device);
4876 	peer_device_statistics_to_skb(skb, &peer_device_statistics);
4877 	genlmsg_end(skb, dh);
4878 	if (multicast) {
4879 		err = drbd_genl_multicast_events(skb, GFP_NOWAIT);
4880 		/* skb has been consumed or freed in netlink_broadcast() */
4881 		if (err && err != -ESRCH)
4882 			goto failed;
4883 	}
4884 	return 0;
4885 
4886 nla_put_failure:
4887 	nlmsg_free(skb);
4888 failed:
4889 	drbd_err(peer_device, "Error %d while broadcasting event. Event seq:%u\n",
4890 		 err, seq);
4891 	return err;
4892 }
4893 
4894 void notify_helper(enum drbd_notification_type type,
4895 		   struct drbd_device *device, struct drbd_connection *connection,
4896 		   const char *name, int status)
4897 {
4898 	struct drbd_resource *resource = device ? device->resource : connection->resource;
4899 	struct drbd_helper_info helper_info;
4900 	unsigned int seq = atomic_inc_return(&notify_genl_seq);
4901 	struct sk_buff *skb = NULL;
4902 	struct drbd_genlmsghdr *dh;
4903 	int err;
4904 
4905 	strscpy(helper_info.helper_name, name, sizeof(helper_info.helper_name));
4906 	helper_info.helper_name_len = min(strlen(name), sizeof(helper_info.helper_name));
4907 	helper_info.helper_status = status;
4908 
4909 	skb = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
4910 	err = -ENOMEM;
4911 	if (!skb)
4912 		goto fail;
4913 
4914 	err = -EMSGSIZE;
4915 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_HELPER);
4916 	if (!dh)
4917 		goto fail;
4918 	dh->minor = device ? device->minor : -1;
4919 	dh->ret_code = NO_ERROR;
4920 	mutex_lock(&notification_mutex);
4921 	if (nla_put_drbd_cfg_context(skb, resource, connection, device) ||
4922 	    nla_put_notification_header(skb, type) ||
4923 	    drbd_helper_info_to_skb(skb, &helper_info))
4924 		goto unlock_fail;
4925 	genlmsg_end(skb, dh);
4926 	err = drbd_genl_multicast_events(skb, GFP_NOWAIT);
4927 	skb = NULL;
4928 	/* skb has been consumed or freed in netlink_broadcast() */
4929 	if (err && err != -ESRCH)
4930 		goto unlock_fail;
4931 	mutex_unlock(&notification_mutex);
4932 	return;
4933 
4934 unlock_fail:
4935 	mutex_unlock(&notification_mutex);
4936 fail:
4937 	nlmsg_free(skb);
4938 	drbd_err(resource, "Error %d while broadcasting event. Event seq:%u\n",
4939 		 err, seq);
4940 }
4941 
4942 static int notify_initial_state_done(struct sk_buff *skb, unsigned int seq)
4943 {
4944 	struct drbd_genlmsghdr *dh;
4945 	int err;
4946 
4947 	err = -EMSGSIZE;
4948 	dh = genlmsg_put(skb, 0, seq, &drbd_nl_family, 0, DRBD_ADM_INITIAL_STATE_DONE);
4949 	if (!dh)
4950 		goto nla_put_failure;
4951 	dh->minor = -1U;
4952 	dh->ret_code = NO_ERROR;
4953 	if (nla_put_notification_header(skb, NOTIFY_EXISTS))
4954 		goto nla_put_failure;
4955 	genlmsg_end(skb, dh);
4956 	return 0;
4957 
4958 nla_put_failure:
4959 	nlmsg_free(skb);
4960 	pr_err("Error %d sending event. Event seq:%u\n", err, seq);
4961 	return err;
4962 }
4963 
4964 static void free_state_changes(struct list_head *list)
4965 {
4966 	while (!list_empty(list)) {
4967 		struct drbd_state_change *state_change =
4968 			list_first_entry(list, struct drbd_state_change, list);
4969 		list_del(&state_change->list);
4970 		forget_state_change(state_change);
4971 	}
4972 }
4973 
4974 static unsigned int notifications_for_state_change(struct drbd_state_change *state_change)
4975 {
4976 	return 1 +
4977 	       state_change->n_connections +
4978 	       state_change->n_devices +
4979 	       state_change->n_devices * state_change->n_connections;
4980 }
4981 
4982 static int get_initial_state(struct sk_buff *skb, struct netlink_callback *cb)
4983 {
4984 	struct drbd_state_change *state_change = (struct drbd_state_change *)cb->args[0];
4985 	unsigned int seq = cb->args[2];
4986 	unsigned int n;
4987 	enum drbd_notification_type flags = 0;
4988 	int err = 0;
4989 
4990 	/* There is no need for taking notification_mutex here: it doesn't
4991 	   matter if the initial state events mix with later state chage
4992 	   events; we can always tell the events apart by the NOTIFY_EXISTS
4993 	   flag. */
4994 
4995 	cb->args[5]--;
4996 	if (cb->args[5] == 1) {
4997 		err = notify_initial_state_done(skb, seq);
4998 		goto out;
4999 	}
5000 	n = cb->args[4]++;
5001 	if (cb->args[4] < cb->args[3])
5002 		flags |= NOTIFY_CONTINUES;
5003 	if (n < 1) {
5004 		err = notify_resource_state_change(skb, seq, state_change->resource,
5005 					     NOTIFY_EXISTS | flags);
5006 		goto next;
5007 	}
5008 	n--;
5009 	if (n < state_change->n_connections) {
5010 		err = notify_connection_state_change(skb, seq, &state_change->connections[n],
5011 					       NOTIFY_EXISTS | flags);
5012 		goto next;
5013 	}
5014 	n -= state_change->n_connections;
5015 	if (n < state_change->n_devices) {
5016 		err = notify_device_state_change(skb, seq, &state_change->devices[n],
5017 					   NOTIFY_EXISTS | flags);
5018 		goto next;
5019 	}
5020 	n -= state_change->n_devices;
5021 	if (n < state_change->n_devices * state_change->n_connections) {
5022 		err = notify_peer_device_state_change(skb, seq, &state_change->peer_devices[n],
5023 						NOTIFY_EXISTS | flags);
5024 		goto next;
5025 	}
5026 
5027 next:
5028 	if (cb->args[4] == cb->args[3]) {
5029 		struct drbd_state_change *next_state_change =
5030 			list_entry(state_change->list.next,
5031 				   struct drbd_state_change, list);
5032 		cb->args[0] = (long)next_state_change;
5033 		cb->args[3] = notifications_for_state_change(next_state_change);
5034 		cb->args[4] = 0;
5035 	}
5036 out:
5037 	if (err)
5038 		return err;
5039 	else
5040 		return skb->len;
5041 }
5042 
5043 int drbd_nl_get_initial_state_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
5044 {
5045 	struct drbd_resource *resource;
5046 	LIST_HEAD(head);
5047 
5048 	if (cb->args[5] >= 1) {
5049 		if (cb->args[5] > 1)
5050 			return get_initial_state(skb, cb);
5051 		if (cb->args[0]) {
5052 			struct drbd_state_change *state_change =
5053 				(struct drbd_state_change *)cb->args[0];
5054 
5055 			/* connect list to head */
5056 			list_add(&head, &state_change->list);
5057 			free_state_changes(&head);
5058 		}
5059 		return 0;
5060 	}
5061 
5062 	cb->args[5] = 2;  /* number of iterations */
5063 	mutex_lock(&resources_mutex);
5064 	for_each_resource(resource, &drbd_resources) {
5065 		struct drbd_state_change *state_change;
5066 
5067 		state_change = remember_old_state(resource, GFP_KERNEL);
5068 		if (!state_change) {
5069 			if (!list_empty(&head))
5070 				free_state_changes(&head);
5071 			mutex_unlock(&resources_mutex);
5072 			return -ENOMEM;
5073 		}
5074 		copy_old_to_new_state_change(state_change);
5075 		list_add_tail(&state_change->list, &head);
5076 		cb->args[5] += notifications_for_state_change(state_change);
5077 	}
5078 	mutex_unlock(&resources_mutex);
5079 
5080 	if (!list_empty(&head)) {
5081 		struct drbd_state_change *state_change =
5082 			list_entry(head.next, struct drbd_state_change, list);
5083 		cb->args[0] = (long)state_change;
5084 		cb->args[3] = notifications_for_state_change(state_change);
5085 		list_del(&head);  /* detach list from head */
5086 	}
5087 
5088 	cb->args[2] = cb->nlh->nlmsg_seq;
5089 	return get_initial_state(skb, cb);
5090 }
5091 
5092 static const struct genl_multicast_group drbd_nl_mcgrps[] = {
5093 	[DRBD_NLGRP_EVENTS] = { .name = "events", },
5094 };
5095 
5096 struct genl_family drbd_nl_family __ro_after_init = {
5097 	.name		= "drbd",
5098 	.version	= DRBD_FAMILY_VERSION,
5099 	.hdrsize	= NLA_ALIGN(sizeof(struct drbd_genlmsghdr)),
5100 	.split_ops	= drbd_nl_ops,
5101 	.n_split_ops	= ARRAY_SIZE(drbd_nl_ops),
5102 	.mcgrps		= drbd_nl_mcgrps,
5103 	.n_mcgrps	= ARRAY_SIZE(drbd_nl_mcgrps),
5104 	.resv_start_op	= 42,
5105 	.module		= THIS_MODULE,
5106 	.netnsok	= true,
5107 };
5108