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