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