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