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