drbd: Consider all crypto options in connect and in net-options
[firefly-linux-kernel-4.4.55.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 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include <linux/genl_magic_func.h>
79
80 /* used blkdev_get_by_path, to claim our meta data device(s) */
81 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
82
83 /* Configuration is strictly serialized, because generic netlink message
84  * processing is strictly serialized by the genl_lock().
85  * Which means we can use one static global drbd_config_context struct.
86  */
87 static struct drbd_config_context {
88         /* assigned from drbd_genlmsghdr */
89         unsigned int minor;
90         /* assigned from request attributes, if present */
91         unsigned int volume;
92 #define VOLUME_UNSPECIFIED              (-1U)
93         /* pointer into the request skb,
94          * limited lifetime! */
95         char *conn_name;
96
97         /* reply buffer */
98         struct sk_buff *reply_skb;
99         /* pointer into reply buffer */
100         struct drbd_genlmsghdr *reply_dh;
101         /* resolved from attributes, if possible */
102         struct drbd_conf *mdev;
103         struct drbd_tconn *tconn;
104 } adm_ctx;
105
106 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
107 {
108         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
109         if (genlmsg_reply(skb, info))
110                 printk(KERN_ERR "drbd: error sending genl reply\n");
111 }
112
113 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
114  * reason it could fail was no space in skb, and there are 4k available. */
115 int drbd_msg_put_info(const char *info)
116 {
117         struct sk_buff *skb = adm_ctx.reply_skb;
118         struct nlattr *nla;
119         int err = -EMSGSIZE;
120
121         if (!info || !info[0])
122                 return 0;
123
124         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
125         if (!nla)
126                 return err;
127
128         err = nla_put_string(skb, T_info_text, info);
129         if (err) {
130                 nla_nest_cancel(skb, nla);
131                 return err;
132         } else
133                 nla_nest_end(skb, nla);
134         return 0;
135 }
136
137 /* This would be a good candidate for a "pre_doit" hook,
138  * and per-family private info->pointers.
139  * But we need to stay compatible with older kernels.
140  * If it returns successfully, adm_ctx members are valid.
141  */
142 #define DRBD_ADM_NEED_MINOR     1
143 #define DRBD_ADM_NEED_CONN      2
144 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
145                 unsigned flags)
146 {
147         struct drbd_genlmsghdr *d_in = info->userhdr;
148         const u8 cmd = info->genlhdr->cmd;
149         int err;
150
151         memset(&adm_ctx, 0, sizeof(adm_ctx));
152
153         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
154         if (cmd != DRBD_ADM_GET_STATUS
155         && security_netlink_recv(skb, CAP_SYS_ADMIN))
156                return -EPERM;
157
158         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
159         if (!adm_ctx.reply_skb)
160                 goto fail;
161
162         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
163                                         info, &drbd_genl_family, 0, cmd);
164         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
165          * but anyways */
166         if (!adm_ctx.reply_dh)
167                 goto fail;
168
169         adm_ctx.reply_dh->minor = d_in->minor;
170         adm_ctx.reply_dh->ret_code = NO_ERROR;
171
172         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
173                 struct nlattr *nla;
174                 /* parse and validate only */
175                 err = drbd_cfg_context_from_attrs(NULL, info);
176                 if (err)
177                         goto fail;
178
179                 /* It was present, and valid,
180                  * copy it over to the reply skb. */
181                 err = nla_put_nohdr(adm_ctx.reply_skb,
182                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
183                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
184                 if (err)
185                         goto fail;
186
187                 /* and assign stuff to the global adm_ctx */
188                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
189                 adm_ctx.volume = nla ? nla_get_u32(nla) : VOLUME_UNSPECIFIED;
190                 nla = nested_attr_tb[__nla_type(T_ctx_conn_name)];
191                 if (nla)
192                         adm_ctx.conn_name = nla_data(nla);
193         } else
194                 adm_ctx.volume = VOLUME_UNSPECIFIED;
195
196         adm_ctx.minor = d_in->minor;
197         adm_ctx.mdev = minor_to_mdev(d_in->minor);
198         adm_ctx.tconn = conn_get_by_name(adm_ctx.conn_name);
199
200         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
201                 drbd_msg_put_info("unknown minor");
202                 return ERR_MINOR_INVALID;
203         }
204         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_CONN)) {
205                 drbd_msg_put_info("unknown connection");
206                 return ERR_INVALID_REQUEST;
207         }
208
209         /* some more paranoia, if the request was over-determined */
210         if (adm_ctx.mdev && adm_ctx.tconn &&
211             adm_ctx.mdev->tconn != adm_ctx.tconn) {
212                 pr_warning("request: minor=%u, conn=%s; but that minor belongs to connection %s\n",
213                                 adm_ctx.minor, adm_ctx.conn_name, adm_ctx.mdev->tconn->name);
214                 drbd_msg_put_info("minor exists in different connection");
215                 return ERR_INVALID_REQUEST;
216         }
217         if (adm_ctx.mdev &&
218             adm_ctx.volume != VOLUME_UNSPECIFIED &&
219             adm_ctx.volume != adm_ctx.mdev->vnr) {
220                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
221                                 adm_ctx.minor, adm_ctx.volume,
222                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
223                 drbd_msg_put_info("minor exists as different volume");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         return NO_ERROR;
228
229 fail:
230         nlmsg_free(adm_ctx.reply_skb);
231         adm_ctx.reply_skb = NULL;
232         return -ENOMEM;
233 }
234
235 static int drbd_adm_finish(struct genl_info *info, int retcode)
236 {
237         struct nlattr *nla;
238         const char *conn_name = NULL;
239
240         if (adm_ctx.tconn) {
241                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
242                 adm_ctx.tconn = NULL;
243         }
244
245         if (!adm_ctx.reply_skb)
246                 return -ENOMEM;
247
248         adm_ctx.reply_dh->ret_code = retcode;
249
250         nla = info->attrs[DRBD_NLA_CFG_CONTEXT];
251         if (nla) {
252                 nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
253                 if (nla)
254                         conn_name = nla_data(nla);
255         }
256
257         drbd_adm_send_reply(adm_ctx.reply_skb, info);
258         return 0;
259 }
260
261 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
262 {
263         char *afs;
264         struct net_conf *nc;
265
266         rcu_read_lock();
267         nc = rcu_dereference(tconn->net_conf);
268         if (nc) {
269                 switch (((struct sockaddr *)nc->peer_addr)->sa_family) {
270                 case AF_INET6:
271                         afs = "ipv6";
272                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
273                                  &((struct sockaddr_in6 *)nc->peer_addr)->sin6_addr);
274                         break;
275                 case AF_INET:
276                         afs = "ipv4";
277                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
278                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
279                         break;
280                 default:
281                         afs = "ssocks";
282                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
283                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
284                 }
285                 snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
286         }
287         rcu_read_unlock();
288 }
289
290 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
291 {
292         char *envp[] = { "HOME=/",
293                         "TERM=linux",
294                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
295                          (char[20]) { }, /* address family */
296                          (char[60]) { }, /* address */
297                         NULL };
298         char mb[12];
299         char *argv[] = {usermode_helper, cmd, mb, NULL };
300         struct sib_info sib;
301         int ret;
302
303         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
304         setup_khelper_env(mdev->tconn, envp);
305
306         /* The helper may take some time.
307          * write out any unsynced meta data changes now */
308         drbd_md_sync(mdev);
309
310         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
311         sib.sib_reason = SIB_HELPER_PRE;
312         sib.helper_name = cmd;
313         drbd_bcast_event(mdev, &sib);
314         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
315         if (ret)
316                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
317                                 usermode_helper, cmd, mb,
318                                 (ret >> 8) & 0xff, ret);
319         else
320                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
321                                 usermode_helper, cmd, mb,
322                                 (ret >> 8) & 0xff, ret);
323         sib.sib_reason = SIB_HELPER_POST;
324         sib.helper_exit_code = ret;
325         drbd_bcast_event(mdev, &sib);
326
327         if (ret < 0) /* Ignore any ERRNOs we got. */
328                 ret = 0;
329
330         return ret;
331 }
332
333 static void conn_md_sync(struct drbd_tconn *tconn)
334 {
335         struct drbd_conf *mdev;
336         int vnr;
337
338         down_read(&drbd_cfg_rwsem);
339         idr_for_each_entry(&tconn->volumes, mdev, vnr)
340                 drbd_md_sync(mdev);
341         up_read(&drbd_cfg_rwsem);
342 }
343
344 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
345 {
346         char *envp[] = { "HOME=/",
347                         "TERM=linux",
348                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
349                          (char[20]) { }, /* address family */
350                          (char[60]) { }, /* address */
351                         NULL };
352         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
353         int ret;
354
355         setup_khelper_env(tconn, envp);
356         conn_md_sync(tconn);
357
358         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
359         /* TODO: conn_bcast_event() ?? */
360
361         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
362         if (ret)
363                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
364                           usermode_helper, cmd, tconn->name,
365                           (ret >> 8) & 0xff, ret);
366         else
367                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
368                           usermode_helper, cmd, tconn->name,
369                           (ret >> 8) & 0xff, ret);
370         /* TODO: conn_bcast_event() ?? */
371
372         if (ret < 0) /* Ignore any ERRNOs we got. */
373                 ret = 0;
374
375         return ret;
376 }
377
378 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
379 {
380         enum drbd_fencing_p fp = FP_NOT_AVAIL;
381         struct drbd_conf *mdev;
382         int vnr;
383
384         rcu_read_lock();
385         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
386                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
387                         fp = max_t(enum drbd_fencing_p, fp, mdev->ldev->dc.fencing);
388                         put_ldev(mdev);
389                 }
390         }
391         rcu_read_unlock();
392
393         return fp;
394 }
395
396 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
397 {
398         union drbd_state mask = { };
399         union drbd_state val = { };
400         enum drbd_fencing_p fp;
401         char *ex_to_string;
402         int r;
403
404         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
405                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
406                 return false;
407         }
408
409         fp = highest_fencing_policy(tconn);
410         switch (fp) {
411         case FP_NOT_AVAIL:
412                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
413                 goto out;
414         case FP_DONT_CARE:
415                 return true;
416         default: ;
417         }
418
419         r = conn_khelper(tconn, "fence-peer");
420
421         switch ((r>>8) & 0xff) {
422         case 3: /* peer is inconsistent */
423                 ex_to_string = "peer is inconsistent or worse";
424                 mask.pdsk = D_MASK;
425                 val.pdsk = D_INCONSISTENT;
426                 break;
427         case 4: /* peer got outdated, or was already outdated */
428                 ex_to_string = "peer was fenced";
429                 mask.pdsk = D_MASK;
430                 val.pdsk = D_OUTDATED;
431                 break;
432         case 5: /* peer was down */
433                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
434                         /* we will(have) create(d) a new UUID anyways... */
435                         ex_to_string = "peer is unreachable, assumed to be dead";
436                         mask.pdsk = D_MASK;
437                         val.pdsk = D_OUTDATED;
438                 } else {
439                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
440                 }
441                 break;
442         case 6: /* Peer is primary, voluntarily outdate myself.
443                  * This is useful when an unconnected R_SECONDARY is asked to
444                  * become R_PRIMARY, but finds the other peer being active. */
445                 ex_to_string = "peer is active";
446                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
447                 mask.disk = D_MASK;
448                 val.disk = D_OUTDATED;
449                 break;
450         case 7:
451                 if (fp != FP_STONITH)
452                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
453                 ex_to_string = "peer was stonithed";
454                 mask.pdsk = D_MASK;
455                 val.pdsk = D_OUTDATED;
456                 break;
457         default:
458                 /* The script is broken ... */
459                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
460                 return false; /* Eventually leave IO frozen */
461         }
462
463         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
464                   (r>>8) & 0xff, ex_to_string);
465
466  out:
467
468         /* Not using
469            conn_request_state(tconn, mask, val, CS_VERBOSE);
470            here, because we might were able to re-establish the connection in the
471            meantime. */
472         spin_lock_irq(&tconn->req_lock);
473         if (tconn->cstate < C_WF_REPORT_PARAMS)
474                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
475         spin_unlock_irq(&tconn->req_lock);
476
477         return conn_highest_pdsk(tconn) <= D_OUTDATED;
478 }
479
480 static int _try_outdate_peer_async(void *data)
481 {
482         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
483
484         conn_try_outdate_peer(tconn);
485
486         kref_put(&tconn->kref, &conn_destroy);
487         return 0;
488 }
489
490 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
491 {
492         struct task_struct *opa;
493
494         kref_get(&tconn->kref);
495         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
496         if (IS_ERR(opa)) {
497                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
498                 kref_put(&tconn->kref, &conn_destroy);
499         }
500 }
501
502 enum drbd_state_rv
503 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
504 {
505         const int max_tries = 4;
506         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
507         struct net_conf *nc;
508         int try = 0;
509         int forced = 0;
510         union drbd_state mask, val;
511
512         if (new_role == R_PRIMARY)
513                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
514
515         mutex_lock(mdev->state_mutex);
516
517         mask.i = 0; mask.role = R_MASK;
518         val.i  = 0; val.role  = new_role;
519
520         while (try++ < max_tries) {
521                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
522
523                 /* in case we first succeeded to outdate,
524                  * but now suddenly could establish a connection */
525                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
526                         val.pdsk = 0;
527                         mask.pdsk = 0;
528                         continue;
529                 }
530
531                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
532                     (mdev->state.disk < D_UP_TO_DATE &&
533                      mdev->state.disk >= D_INCONSISTENT)) {
534                         mask.disk = D_MASK;
535                         val.disk  = D_UP_TO_DATE;
536                         forced = 1;
537                         continue;
538                 }
539
540                 if (rv == SS_NO_UP_TO_DATE_DISK &&
541                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
542                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
543
544                         if (conn_try_outdate_peer(mdev->tconn)) {
545                                 val.disk = D_UP_TO_DATE;
546                                 mask.disk = D_MASK;
547                         }
548                         continue;
549                 }
550
551                 if (rv == SS_NOTHING_TO_DO)
552                         goto out;
553                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
554                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
555                                 dev_warn(DEV, "Forced into split brain situation!\n");
556                                 mask.pdsk = D_MASK;
557                                 val.pdsk  = D_OUTDATED;
558
559                         }
560                         continue;
561                 }
562                 if (rv == SS_TWO_PRIMARIES) {
563                         /* Maybe the peer is detected as dead very soon...
564                            retry at most once more in this case. */
565                         int timeo;
566                         rcu_read_lock();
567                         nc = rcu_dereference(mdev->tconn->net_conf);
568                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
569                         rcu_read_unlock();
570                         schedule_timeout_interruptible(timeo);
571                         if (try < max_tries)
572                                 try = max_tries - 1;
573                         continue;
574                 }
575                 if (rv < SS_SUCCESS) {
576                         rv = _drbd_request_state(mdev, mask, val,
577                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
578                         if (rv < SS_SUCCESS)
579                                 goto out;
580                 }
581                 break;
582         }
583
584         if (rv < SS_SUCCESS)
585                 goto out;
586
587         if (forced)
588                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
589
590         /* Wait until nothing is on the fly :) */
591         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
592
593         if (new_role == R_SECONDARY) {
594                 set_disk_ro(mdev->vdisk, true);
595                 if (get_ldev(mdev)) {
596                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
597                         put_ldev(mdev);
598                 }
599         } else {
600                 mutex_lock(&mdev->tconn->net_conf_update);
601                 nc = mdev->tconn->net_conf;
602                 if (nc)
603                         nc->want_lose = 0; /* without copy; single bit op is atomic */
604                 mutex_unlock(&mdev->tconn->net_conf_update);
605
606                 set_disk_ro(mdev->vdisk, false);
607                 if (get_ldev(mdev)) {
608                         if (((mdev->state.conn < C_CONNECTED ||
609                                mdev->state.pdsk <= D_FAILED)
610                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
611                                 drbd_uuid_new_current(mdev);
612
613                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
614                         put_ldev(mdev);
615                 }
616         }
617
618         /* writeout of activity log covered areas of the bitmap
619          * to stable storage done in after state change already */
620
621         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
622                 /* if this was forced, we should consider sync */
623                 if (forced)
624                         drbd_send_uuids(mdev);
625                 drbd_send_state(mdev);
626         }
627
628         drbd_md_sync(mdev);
629
630         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
631 out:
632         mutex_unlock(mdev->state_mutex);
633         return rv;
634 }
635
636 static const char *from_attrs_err_to_txt(int err)
637 {
638         return  err == -ENOMSG ? "required attribute missing" :
639                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
640                 err == -EEXIST ? "can not change invariant setting" :
641                 "invalid attribute value";
642 }
643
644 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
645 {
646         struct set_role_parms parms;
647         int err;
648         enum drbd_ret_code retcode;
649
650         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
651         if (!adm_ctx.reply_skb)
652                 return retcode;
653         if (retcode != NO_ERROR)
654                 goto out;
655
656         memset(&parms, 0, sizeof(parms));
657         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
658                 err = set_role_parms_from_attrs(&parms, info);
659                 if (err) {
660                         retcode = ERR_MANDATORY_TAG;
661                         drbd_msg_put_info(from_attrs_err_to_txt(err));
662                         goto out;
663                 }
664         }
665
666         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
667                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
668         else
669                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
670 out:
671         drbd_adm_finish(info, retcode);
672         return 0;
673 }
674
675 /* initializes the md.*_offset members, so we are able to find
676  * the on disk meta data */
677 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
678                                        struct drbd_backing_dev *bdev)
679 {
680         sector_t md_size_sect = 0;
681         switch (bdev->dc.meta_dev_idx) {
682         default:
683                 /* v07 style fixed size indexed meta data */
684                 bdev->md.md_size_sect = MD_RESERVED_SECT;
685                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
686                 bdev->md.al_offset = MD_AL_OFFSET;
687                 bdev->md.bm_offset = MD_BM_OFFSET;
688                 break;
689         case DRBD_MD_INDEX_FLEX_EXT:
690                 /* just occupy the full device; unit: sectors */
691                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
692                 bdev->md.md_offset = 0;
693                 bdev->md.al_offset = MD_AL_OFFSET;
694                 bdev->md.bm_offset = MD_BM_OFFSET;
695                 break;
696         case DRBD_MD_INDEX_INTERNAL:
697         case DRBD_MD_INDEX_FLEX_INT:
698                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
699                 /* al size is still fixed */
700                 bdev->md.al_offset = -MD_AL_SECTORS;
701                 /* we need (slightly less than) ~ this much bitmap sectors: */
702                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
703                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
704                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
705                 md_size_sect = ALIGN(md_size_sect, 8);
706
707                 /* plus the "drbd meta data super block",
708                  * and the activity log; */
709                 md_size_sect += MD_BM_OFFSET;
710
711                 bdev->md.md_size_sect = md_size_sect;
712                 /* bitmap offset is adjusted by 'super' block size */
713                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
714                 break;
715         }
716 }
717
718 /* input size is expected to be in KB */
719 char *ppsize(char *buf, unsigned long long size)
720 {
721         /* Needs 9 bytes at max including trailing NUL:
722          * -1ULL ==> "16384 EB" */
723         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
724         int base = 0;
725         while (size >= 10000 && base < sizeof(units)-1) {
726                 /* shift + round */
727                 size = (size >> 10) + !!(size & (1<<9));
728                 base++;
729         }
730         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
731
732         return buf;
733 }
734
735 /* there is still a theoretical deadlock when called from receiver
736  * on an D_INCONSISTENT R_PRIMARY:
737  *  remote READ does inc_ap_bio, receiver would need to receive answer
738  *  packet from remote to dec_ap_bio again.
739  *  receiver receive_sizes(), comes here,
740  *  waits for ap_bio_cnt == 0. -> deadlock.
741  * but this cannot happen, actually, because:
742  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
743  *  (not connected, or bad/no disk on peer):
744  *  see drbd_fail_request_early, ap_bio_cnt is zero.
745  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
746  *  peer may not initiate a resize.
747  */
748 /* Note these are not to be confused with
749  * drbd_adm_suspend_io/drbd_adm_resume_io,
750  * which are (sub) state changes triggered by admin (drbdsetup),
751  * and can be long lived.
752  * This changes an mdev->flag, is triggered by drbd internals,
753  * and should be short-lived. */
754 void drbd_suspend_io(struct drbd_conf *mdev)
755 {
756         set_bit(SUSPEND_IO, &mdev->flags);
757         if (drbd_suspended(mdev))
758                 return;
759         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
760 }
761
762 void drbd_resume_io(struct drbd_conf *mdev)
763 {
764         clear_bit(SUSPEND_IO, &mdev->flags);
765         wake_up(&mdev->misc_wait);
766 }
767
768 /**
769  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
770  * @mdev:       DRBD device.
771  *
772  * Returns 0 on success, negative return values indicate errors.
773  * You should call drbd_md_sync() after calling this function.
774  */
775 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
776 {
777         sector_t prev_first_sect, prev_size; /* previous meta location */
778         sector_t la_size;
779         sector_t size;
780         char ppb[10];
781
782         int md_moved, la_size_changed;
783         enum determine_dev_size rv = unchanged;
784
785         /* race:
786          * application request passes inc_ap_bio,
787          * but then cannot get an AL-reference.
788          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
789          *
790          * to avoid that:
791          * Suspend IO right here.
792          * still lock the act_log to not trigger ASSERTs there.
793          */
794         drbd_suspend_io(mdev);
795
796         /* no wait necessary anymore, actually we could assert that */
797         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
798
799         prev_first_sect = drbd_md_first_sector(mdev->ldev);
800         prev_size = mdev->ldev->md.md_size_sect;
801         la_size = mdev->ldev->md.la_size_sect;
802
803         /* TODO: should only be some assert here, not (re)init... */
804         drbd_md_set_sector_offsets(mdev, mdev->ldev);
805
806         size = drbd_new_dev_size(mdev, mdev->ldev, flags & DDSF_FORCED);
807
808         if (drbd_get_capacity(mdev->this_bdev) != size ||
809             drbd_bm_capacity(mdev) != size) {
810                 int err;
811                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
812                 if (unlikely(err)) {
813                         /* currently there is only one error: ENOMEM! */
814                         size = drbd_bm_capacity(mdev)>>1;
815                         if (size == 0) {
816                                 dev_err(DEV, "OUT OF MEMORY! "
817                                     "Could not allocate bitmap!\n");
818                         } else {
819                                 dev_err(DEV, "BM resizing failed. "
820                                     "Leaving size unchanged at size = %lu KB\n",
821                                     (unsigned long)size);
822                         }
823                         rv = dev_size_error;
824                 }
825                 /* racy, see comments above. */
826                 drbd_set_my_capacity(mdev, size);
827                 mdev->ldev->md.la_size_sect = size;
828                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
829                      (unsigned long long)size>>1);
830         }
831         if (rv == dev_size_error)
832                 goto out;
833
834         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
835
836         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
837                 || prev_size       != mdev->ldev->md.md_size_sect;
838
839         if (la_size_changed || md_moved) {
840                 int err;
841
842                 drbd_al_shrink(mdev); /* All extents inactive. */
843                 dev_info(DEV, "Writing the whole bitmap, %s\n",
844                          la_size_changed && md_moved ? "size changed and md moved" :
845                          la_size_changed ? "size changed" : "md moved");
846                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
847                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
848                                 "size changed", BM_LOCKED_MASK);
849                 if (err) {
850                         rv = dev_size_error;
851                         goto out;
852                 }
853                 drbd_md_mark_dirty(mdev);
854         }
855
856         if (size > la_size)
857                 rv = grew;
858         if (size < la_size)
859                 rv = shrunk;
860 out:
861         lc_unlock(mdev->act_log);
862         wake_up(&mdev->al_wait);
863         drbd_resume_io(mdev);
864
865         return rv;
866 }
867
868 sector_t
869 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev, int assume_peer_has_space)
870 {
871         sector_t p_size = mdev->p_size;   /* partner's disk size. */
872         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
873         sector_t m_size; /* my size */
874         sector_t u_size = bdev->dc.disk_size; /* size requested by user. */
875         sector_t size = 0;
876
877         m_size = drbd_get_max_capacity(bdev);
878
879         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
880                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
881                 p_size = m_size;
882         }
883
884         if (p_size && m_size) {
885                 size = min_t(sector_t, p_size, m_size);
886         } else {
887                 if (la_size) {
888                         size = la_size;
889                         if (m_size && m_size < size)
890                                 size = m_size;
891                         if (p_size && p_size < size)
892                                 size = p_size;
893                 } else {
894                         if (m_size)
895                                 size = m_size;
896                         if (p_size)
897                                 size = p_size;
898                 }
899         }
900
901         if (size == 0)
902                 dev_err(DEV, "Both nodes diskless!\n");
903
904         if (u_size) {
905                 if (u_size > size)
906                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
907                             (unsigned long)u_size>>1, (unsigned long)size>>1);
908                 else
909                         size = u_size;
910         }
911
912         return size;
913 }
914
915 /**
916  * drbd_check_al_size() - Ensures that the AL is of the right size
917  * @mdev:       DRBD device.
918  *
919  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
920  * failed, and 0 on success. You should call drbd_md_sync() after you called
921  * this function.
922  */
923 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
924 {
925         struct lru_cache *n, *t;
926         struct lc_element *e;
927         unsigned int in_use;
928         int i;
929
930         if (!expect(dc->al_extents >= DRBD_AL_EXTENTS_MIN))
931                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
932
933         if (mdev->act_log &&
934             mdev->act_log->nr_elements == dc->al_extents)
935                 return 0;
936
937         in_use = 0;
938         t = mdev->act_log;
939         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
940                 dc->al_extents, sizeof(struct lc_element), 0);
941
942         if (n == NULL) {
943                 dev_err(DEV, "Cannot allocate act_log lru!\n");
944                 return -ENOMEM;
945         }
946         spin_lock_irq(&mdev->al_lock);
947         if (t) {
948                 for (i = 0; i < t->nr_elements; i++) {
949                         e = lc_element_by_index(t, i);
950                         if (e->refcnt)
951                                 dev_err(DEV, "refcnt(%d)==%d\n",
952                                     e->lc_number, e->refcnt);
953                         in_use += e->refcnt;
954                 }
955         }
956         if (!in_use)
957                 mdev->act_log = n;
958         spin_unlock_irq(&mdev->al_lock);
959         if (in_use) {
960                 dev_err(DEV, "Activity log still in use!\n");
961                 lc_destroy(n);
962                 return -EBUSY;
963         } else {
964                 if (t)
965                         lc_destroy(t);
966         }
967         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
968         return 0;
969 }
970
971 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
972 {
973         struct request_queue * const q = mdev->rq_queue;
974         int max_hw_sectors = max_bio_size >> 9;
975         int max_segments = 0;
976
977         if (get_ldev_if_state(mdev, D_ATTACHING)) {
978                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
979
980                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
981                 max_segments = mdev->ldev->dc.max_bio_bvecs;
982                 put_ldev(mdev);
983         }
984
985         blk_queue_logical_block_size(q, 512);
986         blk_queue_max_hw_sectors(q, max_hw_sectors);
987         /* This is the workaround for "bio would need to, but cannot, be split" */
988         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
989         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
990
991         if (get_ldev_if_state(mdev, D_ATTACHING)) {
992                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
993
994                 blk_queue_stack_limits(q, b);
995
996                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
997                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
998                                  q->backing_dev_info.ra_pages,
999                                  b->backing_dev_info.ra_pages);
1000                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1001                 }
1002                 put_ldev(mdev);
1003         }
1004 }
1005
1006 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1007 {
1008         int now, new, local, peer;
1009
1010         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1011         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1012         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1013
1014         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1015                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1016                 mdev->local_max_bio_size = local;
1017                 put_ldev(mdev);
1018         }
1019
1020         /* We may ignore peer limits if the peer is modern enough.
1021            Because new from 8.3.8 onwards the peer can use multiple
1022            BIOs for a single peer_request */
1023         if (mdev->state.conn >= C_CONNECTED) {
1024                 if (mdev->tconn->agreed_pro_version < 94)
1025                         peer = mdev->peer_max_bio_size;
1026                 else if (mdev->tconn->agreed_pro_version == 94)
1027                         peer = DRBD_MAX_SIZE_H80_PACKET;
1028                 else /* drbd 8.3.8 onwards */
1029                         peer = DRBD_MAX_BIO_SIZE;
1030         }
1031
1032         new = min_t(int, local, peer);
1033
1034         if (mdev->state.role == R_PRIMARY && new < now)
1035                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1036
1037         if (new != now)
1038                 dev_info(DEV, "max BIO size = %u\n", new);
1039
1040         drbd_setup_queue_param(mdev, new);
1041 }
1042
1043 /* Starts the worker thread */
1044 static void conn_reconfig_start(struct drbd_tconn *tconn)
1045 {
1046         drbd_thread_start(&tconn->worker);
1047         conn_flush_workqueue(tconn);
1048 }
1049
1050 /* if still unconfigured, stops worker again. */
1051 static void conn_reconfig_done(struct drbd_tconn *tconn)
1052 {
1053         spin_lock_irq(&tconn->req_lock);
1054         if (conn_all_vols_unconf(tconn))
1055                 drbd_thread_stop_nowait(&tconn->worker);
1056         spin_unlock_irq(&tconn->req_lock);
1057 }
1058
1059 /* Make sure IO is suspended before calling this function(). */
1060 static void drbd_suspend_al(struct drbd_conf *mdev)
1061 {
1062         int s = 0;
1063
1064         if (!lc_try_lock(mdev->act_log)) {
1065                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1066                 return;
1067         }
1068
1069         drbd_al_shrink(mdev);
1070         spin_lock_irq(&mdev->tconn->req_lock);
1071         if (mdev->state.conn < C_CONNECTED)
1072                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1073         spin_unlock_irq(&mdev->tconn->req_lock);
1074         lc_unlock(mdev->act_log);
1075
1076         if (s)
1077                 dev_info(DEV, "Suspended AL updates\n");
1078 }
1079
1080 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1081 {
1082         enum drbd_ret_code retcode;
1083         struct drbd_conf *mdev;
1084         struct disk_conf *ndc; /* new disk conf */
1085         int err, fifo_size;
1086         int *rs_plan_s = NULL;
1087
1088         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1089         if (!adm_ctx.reply_skb)
1090                 return retcode;
1091         if (retcode != NO_ERROR)
1092                 goto out;
1093
1094         mdev = adm_ctx.mdev;
1095
1096         /* we also need a disk
1097          * to change the options on */
1098         if (!get_ldev(mdev)) {
1099                 retcode = ERR_NO_DISK;
1100                 goto out;
1101         }
1102
1103 /* FIXME freeze IO, cluster wide.
1104  *
1105  * We should make sure no-one uses
1106  * some half-updated struct when we
1107  * assign it later. */
1108
1109         ndc = kmalloc(sizeof(*ndc), GFP_KERNEL);
1110         if (!ndc) {
1111                 retcode = ERR_NOMEM;
1112                 goto fail;
1113         }
1114
1115         memcpy(ndc, &mdev->ldev->dc, sizeof(*ndc));
1116         err = disk_conf_from_attrs_for_change(ndc, info);
1117         if (err) {
1118                 retcode = ERR_MANDATORY_TAG;
1119                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1120         }
1121
1122         if (!expect(ndc->resync_rate >= 1))
1123                 ndc->resync_rate = 1;
1124
1125         /* clip to allowed range */
1126         if (!expect(ndc->al_extents >= DRBD_AL_EXTENTS_MIN))
1127                 ndc->al_extents = DRBD_AL_EXTENTS_MIN;
1128         if (!expect(ndc->al_extents <= DRBD_AL_EXTENTS_MAX))
1129                 ndc->al_extents = DRBD_AL_EXTENTS_MAX;
1130
1131         /* most sanity checks done, try to assign the new sync-after
1132          * dependency.  need to hold the global lock in there,
1133          * to avoid a race in the dependency loop check. */
1134         retcode = drbd_alter_sa(mdev, ndc->resync_after);
1135         if (retcode != NO_ERROR)
1136                 goto fail;
1137
1138         fifo_size = (ndc->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1139         if (fifo_size != mdev->rs_plan_s.size && fifo_size > 0) {
1140                 rs_plan_s   = kzalloc(sizeof(int) * fifo_size, GFP_KERNEL);
1141                 if (!rs_plan_s) {
1142                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1143                         retcode = ERR_NOMEM;
1144                         goto fail;
1145                 }
1146         }
1147
1148         if (fifo_size != mdev->rs_plan_s.size) {
1149                 kfree(mdev->rs_plan_s.values);
1150                 mdev->rs_plan_s.values = rs_plan_s;
1151                 mdev->rs_plan_s.size   = fifo_size;
1152                 mdev->rs_planed = 0;
1153                 rs_plan_s = NULL;
1154         }
1155
1156         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1157         drbd_al_shrink(mdev);
1158         err = drbd_check_al_size(mdev, ndc);
1159         lc_unlock(mdev->act_log);
1160         wake_up(&mdev->al_wait);
1161
1162         if (err) {
1163                 retcode = ERR_NOMEM;
1164                 goto fail;
1165         }
1166
1167         /* FIXME
1168          * To avoid someone looking at a half-updated struct, we probably
1169          * should have a rw-semaphor on net_conf and disk_conf.
1170          */
1171         mdev->ldev->dc = *ndc;
1172
1173         drbd_md_sync(mdev);
1174
1175
1176         if (mdev->state.conn >= C_CONNECTED)
1177                 drbd_send_sync_param(mdev);
1178
1179  fail:
1180         put_ldev(mdev);
1181         kfree(ndc);
1182         kfree(rs_plan_s);
1183  out:
1184         drbd_adm_finish(info, retcode);
1185         return 0;
1186 }
1187
1188 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1189 {
1190         struct drbd_conf *mdev;
1191         int err;
1192         enum drbd_ret_code retcode;
1193         enum determine_dev_size dd;
1194         sector_t max_possible_sectors;
1195         sector_t min_md_device_sectors;
1196         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1197         struct block_device *bdev;
1198         struct lru_cache *resync_lru = NULL;
1199         union drbd_state ns, os;
1200         enum drbd_state_rv rv;
1201         struct net_conf *nc;
1202         int cp_discovered = 0;
1203
1204         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1205         if (!adm_ctx.reply_skb)
1206                 return retcode;
1207         if (retcode != NO_ERROR)
1208                 goto finish;
1209
1210         mdev = adm_ctx.mdev;
1211         conn_reconfig_start(mdev->tconn);
1212
1213         /* if you want to reconfigure, please tear down first */
1214         if (mdev->state.disk > D_DISKLESS) {
1215                 retcode = ERR_DISK_CONFIGURED;
1216                 goto fail;
1217         }
1218         /* It may just now have detached because of IO error.  Make sure
1219          * drbd_ldev_destroy is done already, we may end up here very fast,
1220          * e.g. if someone calls attach from the on-io-error handler,
1221          * to realize a "hot spare" feature (not that I'd recommend that) */
1222         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1223
1224         /* allocation not in the IO path, drbdsetup context */
1225         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1226         if (!nbc) {
1227                 retcode = ERR_NOMEM;
1228                 goto fail;
1229         }
1230
1231         nbc->dc = (struct disk_conf) {
1232                 {}, 0, /* backing_dev */
1233                 {}, 0, /* meta_dev */
1234                 0, /* meta_dev_idx */
1235                 DRBD_DISK_SIZE_SECT_DEF, /* disk_size */
1236                 DRBD_MAX_BIO_BVECS_DEF, /* max_bio_bvecs */
1237                 DRBD_ON_IO_ERROR_DEF, /* on_io_error */
1238                 DRBD_FENCING_DEF, /* fencing */
1239                 DRBD_RATE_DEF, /* resync_rate */
1240                 DRBD_AFTER_DEF, /* resync_after */
1241                 DRBD_AL_EXTENTS_DEF, /* al_extents */
1242                 DRBD_C_PLAN_AHEAD_DEF, /* c_plan_ahead */
1243                 DRBD_C_DELAY_TARGET_DEF, /* c_delay_target */
1244                 DRBD_C_FILL_TARGET_DEF, /* c_fill_target */
1245                 DRBD_C_MAX_RATE_DEF, /* c_max_rate */
1246                 DRBD_C_MIN_RATE_DEF, /* c_min_rate */
1247                 0, /* no_disk_barrier */
1248                 0, /* no_disk_flush */
1249                 0, /* no_disk_drain */
1250                 0, /* no_md_flush */
1251         };
1252
1253         err = disk_conf_from_attrs(&nbc->dc, info);
1254         if (err) {
1255                 retcode = ERR_MANDATORY_TAG;
1256                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1257                 goto fail;
1258         }
1259
1260         if ((int)nbc->dc.meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1261                 retcode = ERR_MD_IDX_INVALID;
1262                 goto fail;
1263         }
1264
1265         rcu_read_lock();
1266         nc = rcu_dereference(mdev->tconn->net_conf);
1267         if (nc) {
1268                 if (nbc->dc.fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1269                         rcu_read_unlock();
1270                         retcode = ERR_STONITH_AND_PROT_A;
1271                         goto fail;
1272                 }
1273         }
1274         rcu_read_unlock();
1275
1276         bdev = blkdev_get_by_path(nbc->dc.backing_dev,
1277                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1278         if (IS_ERR(bdev)) {
1279                 dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.backing_dev,
1280                         PTR_ERR(bdev));
1281                 retcode = ERR_OPEN_DISK;
1282                 goto fail;
1283         }
1284         nbc->backing_bdev = bdev;
1285
1286         /*
1287          * meta_dev_idx >= 0: external fixed size, possibly multiple
1288          * drbd sharing one meta device.  TODO in that case, paranoia
1289          * check that [md_bdev, meta_dev_idx] is not yet used by some
1290          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1291          * should check it for you already; but if you don't, or
1292          * someone fooled it, we need to double check here)
1293          */
1294         bdev = blkdev_get_by_path(nbc->dc.meta_dev,
1295                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1296                                   ((int)nbc->dc.meta_dev_idx < 0) ?
1297                                   (void *)mdev : (void *)drbd_m_holder);
1298         if (IS_ERR(bdev)) {
1299                 dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.meta_dev,
1300                         PTR_ERR(bdev));
1301                 retcode = ERR_OPEN_MD_DISK;
1302                 goto fail;
1303         }
1304         nbc->md_bdev = bdev;
1305
1306         if ((nbc->backing_bdev == nbc->md_bdev) !=
1307             (nbc->dc.meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1308              nbc->dc.meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1309                 retcode = ERR_MD_IDX_INVALID;
1310                 goto fail;
1311         }
1312
1313         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1314                         1, 61, sizeof(struct bm_extent),
1315                         offsetof(struct bm_extent, lce));
1316         if (!resync_lru) {
1317                 retcode = ERR_NOMEM;
1318                 goto fail;
1319         }
1320
1321         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1322         drbd_md_set_sector_offsets(mdev, nbc);
1323
1324         if (drbd_get_max_capacity(nbc) < nbc->dc.disk_size) {
1325                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1326                         (unsigned long long) drbd_get_max_capacity(nbc),
1327                         (unsigned long long) nbc->dc.disk_size);
1328                 retcode = ERR_DISK_TO_SMALL;
1329                 goto fail;
1330         }
1331
1332         if ((int)nbc->dc.meta_dev_idx < 0) {
1333                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1334                 /* at least one MB, otherwise it does not make sense */
1335                 min_md_device_sectors = (2<<10);
1336         } else {
1337                 max_possible_sectors = DRBD_MAX_SECTORS;
1338                 min_md_device_sectors = MD_RESERVED_SECT * (nbc->dc.meta_dev_idx + 1);
1339         }
1340
1341         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1342                 retcode = ERR_MD_DISK_TO_SMALL;
1343                 dev_warn(DEV, "refusing attach: md-device too small, "
1344                      "at least %llu sectors needed for this meta-disk type\n",
1345                      (unsigned long long) min_md_device_sectors);
1346                 goto fail;
1347         }
1348
1349         /* Make sure the new disk is big enough
1350          * (we may currently be R_PRIMARY with no local disk...) */
1351         if (drbd_get_max_capacity(nbc) <
1352             drbd_get_capacity(mdev->this_bdev)) {
1353                 retcode = ERR_DISK_TO_SMALL;
1354                 goto fail;
1355         }
1356
1357         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1358
1359         if (nbc->known_size > max_possible_sectors) {
1360                 dev_warn(DEV, "==> truncating very big lower level device "
1361                         "to currently maximum possible %llu sectors <==\n",
1362                         (unsigned long long) max_possible_sectors);
1363                 if ((int)nbc->dc.meta_dev_idx >= 0)
1364                         dev_warn(DEV, "==>> using internal or flexible "
1365                                       "meta data may help <<==\n");
1366         }
1367
1368         drbd_suspend_io(mdev);
1369         /* also wait for the last barrier ack. */
1370         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1371         /* and for any other previously queued work */
1372         drbd_flush_workqueue(mdev);
1373
1374         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1375         retcode = rv;  /* FIXME: Type mismatch. */
1376         drbd_resume_io(mdev);
1377         if (rv < SS_SUCCESS)
1378                 goto fail;
1379
1380         if (!get_ldev_if_state(mdev, D_ATTACHING))
1381                 goto force_diskless;
1382
1383         drbd_md_set_sector_offsets(mdev, nbc);
1384
1385         if (!mdev->bitmap) {
1386                 if (drbd_bm_init(mdev)) {
1387                         retcode = ERR_NOMEM;
1388                         goto force_diskless_dec;
1389                 }
1390         }
1391
1392         retcode = drbd_md_read(mdev, nbc);
1393         if (retcode != NO_ERROR)
1394                 goto force_diskless_dec;
1395
1396         if (mdev->state.conn < C_CONNECTED &&
1397             mdev->state.role == R_PRIMARY &&
1398             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1399                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1400                     (unsigned long long)mdev->ed_uuid);
1401                 retcode = ERR_DATA_NOT_CURRENT;
1402                 goto force_diskless_dec;
1403         }
1404
1405         /* Since we are diskless, fix the activity log first... */
1406         if (drbd_check_al_size(mdev, &nbc->dc)) {
1407                 retcode = ERR_NOMEM;
1408                 goto force_diskless_dec;
1409         }
1410
1411         /* Prevent shrinking of consistent devices ! */
1412         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1413             drbd_new_dev_size(mdev, nbc, 0) < nbc->md.la_size_sect) {
1414                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1415                 retcode = ERR_DISK_TO_SMALL;
1416                 goto force_diskless_dec;
1417         }
1418
1419         if (!drbd_al_read_log(mdev, nbc)) {
1420                 retcode = ERR_IO_MD_DISK;
1421                 goto force_diskless_dec;
1422         }
1423
1424         /* Reset the "barriers don't work" bits here, then force meta data to
1425          * be written, to ensure we determine if barriers are supported. */
1426         if (nbc->dc.no_md_flush)
1427                 set_bit(MD_NO_FUA, &mdev->flags);
1428         else
1429                 clear_bit(MD_NO_FUA, &mdev->flags);
1430
1431         /* Point of no return reached.
1432          * Devices and memory are no longer released by error cleanup below.
1433          * now mdev takes over responsibility, and the state engine should
1434          * clean it up somewhere.  */
1435         D_ASSERT(mdev->ldev == NULL);
1436         mdev->ldev = nbc;
1437         mdev->resync = resync_lru;
1438         nbc = NULL;
1439         resync_lru = NULL;
1440
1441         mdev->write_ordering = WO_bdev_flush;
1442         drbd_bump_write_ordering(mdev, WO_bdev_flush);
1443
1444         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1445                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1446         else
1447                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1448
1449         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1450             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod)) {
1451                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1452                 cp_discovered = 1;
1453         }
1454
1455         mdev->send_cnt = 0;
1456         mdev->recv_cnt = 0;
1457         mdev->read_cnt = 0;
1458         mdev->writ_cnt = 0;
1459
1460         drbd_reconsider_max_bio_size(mdev);
1461
1462         /* If I am currently not R_PRIMARY,
1463          * but meta data primary indicator is set,
1464          * I just now recover from a hard crash,
1465          * and have been R_PRIMARY before that crash.
1466          *
1467          * Now, if I had no connection before that crash
1468          * (have been degraded R_PRIMARY), chances are that
1469          * I won't find my peer now either.
1470          *
1471          * In that case, and _only_ in that case,
1472          * we use the degr-wfc-timeout instead of the default,
1473          * so we can automatically recover from a crash of a
1474          * degraded but active "cluster" after a certain timeout.
1475          */
1476         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1477         if (mdev->state.role != R_PRIMARY &&
1478              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1479             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1480                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1481
1482         dd = drbd_determine_dev_size(mdev, 0);
1483         if (dd == dev_size_error) {
1484                 retcode = ERR_NOMEM_BITMAP;
1485                 goto force_diskless_dec;
1486         } else if (dd == grew)
1487                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1488
1489         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1490                 dev_info(DEV, "Assuming that all blocks are out of sync "
1491                      "(aka FullSync)\n");
1492                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1493                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1494                         retcode = ERR_IO_MD_DISK;
1495                         goto force_diskless_dec;
1496                 }
1497         } else {
1498                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1499                         "read from attaching", BM_LOCKED_MASK)) {
1500                         retcode = ERR_IO_MD_DISK;
1501                         goto force_diskless_dec;
1502                 }
1503         }
1504
1505         if (cp_discovered) {
1506                 drbd_al_apply_to_bm(mdev);
1507                 if (drbd_bitmap_io(mdev, &drbd_bm_write,
1508                         "crashed primary apply AL", BM_LOCKED_MASK)) {
1509                         retcode = ERR_IO_MD_DISK;
1510                         goto force_diskless_dec;
1511                 }
1512         }
1513
1514         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1515                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1516
1517         spin_lock_irq(&mdev->tconn->req_lock);
1518         os = drbd_read_state(mdev);
1519         ns = os;
1520         /* If MDF_CONSISTENT is not set go into inconsistent state,
1521            otherwise investigate MDF_WasUpToDate...
1522            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1523            otherwise into D_CONSISTENT state.
1524         */
1525         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1526                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1527                         ns.disk = D_CONSISTENT;
1528                 else
1529                         ns.disk = D_OUTDATED;
1530         } else {
1531                 ns.disk = D_INCONSISTENT;
1532         }
1533
1534         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1535                 ns.pdsk = D_OUTDATED;
1536
1537         if ( ns.disk == D_CONSISTENT &&
1538             (ns.pdsk == D_OUTDATED || mdev->ldev->dc.fencing == FP_DONT_CARE))
1539                 ns.disk = D_UP_TO_DATE;
1540
1541         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1542            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1543            this point, because drbd_request_state() modifies these
1544            flags. */
1545
1546         /* In case we are C_CONNECTED postpone any decision on the new disk
1547            state after the negotiation phase. */
1548         if (mdev->state.conn == C_CONNECTED) {
1549                 mdev->new_state_tmp.i = ns.i;
1550                 ns.i = os.i;
1551                 ns.disk = D_NEGOTIATING;
1552
1553                 /* We expect to receive up-to-date UUIDs soon.
1554                    To avoid a race in receive_state, free p_uuid while
1555                    holding req_lock. I.e. atomic with the state change */
1556                 kfree(mdev->p_uuid);
1557                 mdev->p_uuid = NULL;
1558         }
1559
1560         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1561         spin_unlock_irq(&mdev->tconn->req_lock);
1562
1563         if (rv < SS_SUCCESS)
1564                 goto force_diskless_dec;
1565
1566         if (mdev->state.role == R_PRIMARY)
1567                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1568         else
1569                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1570
1571         drbd_md_mark_dirty(mdev);
1572         drbd_md_sync(mdev);
1573
1574         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1575         put_ldev(mdev);
1576         conn_reconfig_done(mdev->tconn);
1577         drbd_adm_finish(info, retcode);
1578         return 0;
1579
1580  force_diskless_dec:
1581         put_ldev(mdev);
1582  force_diskless:
1583         drbd_force_state(mdev, NS(disk, D_FAILED));
1584         drbd_md_sync(mdev);
1585  fail:
1586         conn_reconfig_done(mdev->tconn);
1587         if (nbc) {
1588                 if (nbc->backing_bdev)
1589                         blkdev_put(nbc->backing_bdev,
1590                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1591                 if (nbc->md_bdev)
1592                         blkdev_put(nbc->md_bdev,
1593                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1594                 kfree(nbc);
1595         }
1596         lc_destroy(resync_lru);
1597
1598  finish:
1599         drbd_adm_finish(info, retcode);
1600         return 0;
1601 }
1602
1603 static int adm_detach(struct drbd_conf *mdev)
1604 {
1605         enum drbd_state_rv retcode;
1606         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1607         retcode = drbd_request_state(mdev, NS(disk, D_DISKLESS));
1608         wait_event(mdev->misc_wait,
1609                         mdev->state.disk != D_DISKLESS ||
1610                         !atomic_read(&mdev->local_cnt));
1611         drbd_resume_io(mdev);
1612         return retcode;
1613 }
1614
1615 /* Detaching the disk is a process in multiple stages.  First we need to lock
1616  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1617  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1618  * internal references as well.
1619  * Only then we have finally detached. */
1620 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1621 {
1622         enum drbd_ret_code retcode;
1623
1624         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1625         if (!adm_ctx.reply_skb)
1626                 return retcode;
1627         if (retcode != NO_ERROR)
1628                 goto out;
1629
1630         retcode = adm_detach(adm_ctx.mdev);
1631 out:
1632         drbd_adm_finish(info, retcode);
1633         return 0;
1634 }
1635
1636 static bool conn_resync_running(struct drbd_tconn *tconn)
1637 {
1638         struct drbd_conf *mdev;
1639         bool rv = false;
1640         int vnr;
1641
1642         rcu_read_lock();
1643         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1644                 if (mdev->state.conn == C_SYNC_SOURCE ||
1645                     mdev->state.conn == C_SYNC_TARGET ||
1646                     mdev->state.conn == C_PAUSED_SYNC_S ||
1647                     mdev->state.conn == C_PAUSED_SYNC_T) {
1648                         rv = true;
1649                         break;
1650                 }
1651         }
1652         rcu_read_unlock();
1653
1654         return rv;
1655 }
1656
1657 static bool conn_ov_running(struct drbd_tconn *tconn)
1658 {
1659         struct drbd_conf *mdev;
1660         bool rv = false;
1661         int vnr;
1662
1663         rcu_read_lock();
1664         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1665                 if (mdev->state.conn == C_VERIFY_S ||
1666                     mdev->state.conn == C_VERIFY_T) {
1667                         rv = true;
1668                         break;
1669                 }
1670         }
1671         rcu_read_unlock();
1672
1673         return rv;
1674 }
1675
1676 static enum drbd_ret_code
1677 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1678 {
1679         struct drbd_conf *mdev;
1680         int i;
1681
1682         if (old_conf && tconn->agreed_pro_version < 100 &&
1683             tconn->cstate == C_WF_REPORT_PARAMS &&
1684             new_conf->wire_protocol != old_conf->wire_protocol)
1685                 return ERR_NEED_APV_100;
1686
1687         if (new_conf->two_primaries &&
1688             (new_conf->wire_protocol != DRBD_PROT_C))
1689                 return ERR_NOT_PROTO_C;
1690
1691         idr_for_each_entry(&tconn->volumes, mdev, i) {
1692                 if (get_ldev(mdev)) {
1693                         enum drbd_fencing_p fp = mdev->ldev->dc.fencing;
1694                         put_ldev(mdev);
1695                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1696                                 return ERR_STONITH_AND_PROT_A;
1697                 }
1698                 if (mdev->state.role == R_PRIMARY && new_conf->want_lose)
1699                         return ERR_DISCARD;
1700         }
1701
1702         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1703                 return ERR_CONG_NOT_PROTO_A;
1704
1705         return NO_ERROR;
1706 }
1707
1708 static enum drbd_ret_code
1709 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1710 {
1711         static enum drbd_ret_code rv;
1712         struct drbd_conf *mdev;
1713         int i;
1714
1715         rcu_read_lock();
1716         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1717         rcu_read_unlock();
1718
1719         /* tconn->volumes protected by genl_lock() here */
1720         idr_for_each_entry(&tconn->volumes, mdev, i) {
1721                 if (!mdev->bitmap) {
1722                         if(drbd_bm_init(mdev))
1723                                 return ERR_NOMEM;
1724                 }
1725         }
1726
1727         return rv;
1728 }
1729
1730 struct crypto {
1731         struct crypto_hash *verify_tfm;
1732         struct crypto_hash *csums_tfm;
1733         struct crypto_hash *cram_hmac_tfm;
1734         struct crypto_hash *integrity_w_tfm;
1735         struct crypto_hash *integrity_r_tfm;
1736         void *int_dig_in;
1737         void *int_dig_vv;
1738 };
1739
1740 static int
1741 alloc_tfm(struct crypto_hash **tfm, char *tfm_name, int err_alg, int err_nd)
1742 {
1743         if (!tfm_name[0])
1744                 return NO_ERROR;
1745
1746         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1747         if (IS_ERR(*tfm)) {
1748                 *tfm = NULL;
1749                 return err_alg;
1750         }
1751
1752         if (!drbd_crypto_is_hash(crypto_hash_tfm(*tfm)))
1753                 return err_nd;
1754
1755         return NO_ERROR;
1756 }
1757
1758 static enum drbd_ret_code
1759 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1760 {
1761         char hmac_name[CRYPTO_MAX_ALG_NAME];
1762         enum drbd_ret_code rv;
1763         int hash_size;
1764
1765         rv = alloc_tfm(&crypto->csums_tfm, new_conf->csums_alg,
1766                        ERR_CSUMS_ALG, ERR_CSUMS_ALG_ND);
1767         if (rv != NO_ERROR)
1768                 return rv;
1769         rv = alloc_tfm(&crypto->verify_tfm, new_conf->verify_alg,
1770                        ERR_VERIFY_ALG, ERR_VERIFY_ALG_ND);
1771         if (rv != NO_ERROR)
1772                 return rv;
1773         rv = alloc_tfm(&crypto->integrity_w_tfm, new_conf->integrity_alg,
1774                        ERR_INTEGRITY_ALG, ERR_INTEGRITY_ALG_ND);
1775         if (rv != NO_ERROR)
1776                 return rv;
1777         rv = alloc_tfm(&crypto->integrity_r_tfm, new_conf->integrity_alg,
1778                        ERR_INTEGRITY_ALG, ERR_INTEGRITY_ALG_ND);
1779         if (rv != NO_ERROR)
1780                 return rv;
1781         if (new_conf->cram_hmac_alg[0] != 0) {
1782                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1783                          new_conf->cram_hmac_alg);
1784
1785                 rv = alloc_tfm(&crypto->cram_hmac_tfm, hmac_name,
1786                                ERR_AUTH_ALG, ERR_AUTH_ALG_ND);
1787         }
1788         if (crypto->integrity_w_tfm) {
1789                 hash_size = crypto_hash_digestsize(crypto->integrity_w_tfm);
1790                 crypto->int_dig_in = kmalloc(hash_size, GFP_KERNEL);
1791                 if (!crypto->int_dig_in)
1792                         return ERR_NOMEM;
1793                 crypto->int_dig_vv = kmalloc(hash_size, GFP_KERNEL);
1794                 if (!crypto->int_dig_vv)
1795                         return ERR_NOMEM;
1796         }
1797
1798         return rv;
1799 }
1800
1801 static void free_crypto(struct crypto *crypto)
1802 {
1803         kfree(crypto->int_dig_in);
1804         kfree(crypto->int_dig_vv);
1805         crypto_free_hash(crypto->cram_hmac_tfm);
1806         crypto_free_hash(crypto->integrity_w_tfm);
1807         crypto_free_hash(crypto->integrity_r_tfm);
1808         crypto_free_hash(crypto->csums_tfm);
1809         crypto_free_hash(crypto->verify_tfm);
1810 }
1811
1812 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1813 {
1814         enum drbd_ret_code retcode;
1815         struct drbd_tconn *tconn;
1816         struct net_conf *old_conf, *new_conf = NULL;
1817         int err;
1818         int ovr; /* online verify running */
1819         int rsr; /* re-sync running */
1820         struct crypto crypto = { };
1821
1822         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1823         if (!adm_ctx.reply_skb)
1824                 return retcode;
1825         if (retcode != NO_ERROR)
1826                 goto out;
1827
1828         tconn = adm_ctx.tconn;
1829
1830         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1831         if (!new_conf) {
1832                 retcode = ERR_NOMEM;
1833                 goto out;
1834         }
1835
1836         conn_reconfig_start(tconn);
1837
1838         mutex_lock(&tconn->net_conf_update);
1839         old_conf = tconn->net_conf;
1840
1841         if (!old_conf) {
1842                 drbd_msg_put_info("net conf missing, try connect");
1843                 retcode = ERR_INVALID_REQUEST;
1844                 goto fail;
1845         }
1846
1847         *new_conf = *old_conf;
1848
1849         err = net_conf_from_attrs_for_change(new_conf, info);
1850         if (err) {
1851                 retcode = ERR_MANDATORY_TAG;
1852                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1853                 goto fail;
1854         }
1855
1856         retcode = check_net_options(tconn, new_conf);
1857         if (retcode != NO_ERROR)
1858                 goto fail;
1859
1860         /* re-sync running */
1861         rsr = conn_resync_running(tconn);
1862         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1863                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1864                 goto fail;
1865         }
1866
1867         /* online verify running */
1868         ovr = conn_ov_running(tconn);
1869         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1870                 retcode = ERR_VERIFY_RUNNING;
1871                 goto fail;
1872         }
1873
1874         retcode = alloc_crypto(&crypto, new_conf);
1875         if (retcode != NO_ERROR)
1876                 goto fail;
1877
1878         rcu_assign_pointer(tconn->net_conf, new_conf);
1879
1880         if (!rsr) {
1881                 crypto_free_hash(tconn->csums_tfm);
1882                 tconn->csums_tfm = crypto.csums_tfm;
1883                 crypto.csums_tfm = NULL;
1884         }
1885         if (!ovr) {
1886                 crypto_free_hash(tconn->verify_tfm);
1887                 tconn->verify_tfm = crypto.verify_tfm;
1888                 crypto.verify_tfm = NULL;
1889         }
1890
1891         /* FIXME can not assign these so bluntly while we have ongoing IO */
1892         kfree(tconn->int_dig_in);
1893         tconn->int_dig_in = crypto.int_dig_in;
1894         kfree(tconn->int_dig_vv);
1895         tconn->int_dig_vv = crypto.int_dig_vv;
1896         crypto_free_hash(tconn->integrity_w_tfm);
1897         tconn->integrity_w_tfm = crypto.integrity_w_tfm;
1898         crypto_free_hash(tconn->integrity_r_tfm);
1899         tconn->integrity_r_tfm = crypto.integrity_r_tfm;
1900
1901         /* FIXME Changing cram_hmac while the connection is established is useless */
1902         crypto_free_hash(tconn->cram_hmac_tfm);
1903         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1904
1905         mutex_unlock(&tconn->net_conf_update);
1906         synchronize_rcu();
1907         kfree(old_conf);
1908
1909         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1910                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
1911
1912         goto done;
1913
1914  fail:
1915         mutex_unlock(&tconn->net_conf_update);
1916         free_crypto(&crypto);
1917         kfree(new_conf);
1918  done:
1919         conn_reconfig_done(tconn);
1920  out:
1921         drbd_adm_finish(info, retcode);
1922         return 0;
1923 }
1924
1925 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
1926 {
1927         struct drbd_conf *mdev;
1928         struct net_conf *old_conf, *new_conf = NULL;
1929         struct crypto crypto = { };
1930         struct drbd_tconn *oconn;
1931         struct drbd_tconn *tconn;
1932         struct sockaddr *new_my_addr, *new_peer_addr, *taken_addr;
1933         enum drbd_ret_code retcode;
1934         int i;
1935         int err;
1936
1937         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1938         if (!adm_ctx.reply_skb)
1939                 return retcode;
1940         if (retcode != NO_ERROR)
1941                 goto out;
1942
1943         tconn = adm_ctx.tconn;
1944         conn_reconfig_start(tconn);
1945
1946         if (tconn->cstate > C_STANDALONE) {
1947                 retcode = ERR_NET_CONFIGURED;
1948                 goto fail;
1949         }
1950
1951         /* allocation not in the IO path, cqueue thread context */
1952         new_conf = kmalloc(sizeof(struct net_conf), GFP_KERNEL);
1953         if (!new_conf) {
1954                 retcode = ERR_NOMEM;
1955                 goto fail;
1956         }
1957
1958         *new_conf = (struct net_conf) {
1959                 {}, 0, /* my_addr */
1960                 {}, 0, /* peer_addr */
1961                 {}, 0, /* shared_secret */
1962                 {}, 0, /* cram_hmac_alg */
1963                 {}, 0, /* integrity_alg */
1964                 {}, 0, /* verify_alg */
1965                 {}, 0, /* csums_alg */
1966                 DRBD_PROTOCOL_DEF, /* wire_protocol */
1967                 DRBD_CONNECT_INT_DEF, /* try_connect_int */
1968                 DRBD_TIMEOUT_DEF, /* timeout */
1969                 DRBD_PING_INT_DEF, /* ping_int */
1970                 DRBD_PING_TIMEO_DEF, /* ping_timeo */
1971                 DRBD_SNDBUF_SIZE_DEF, /* sndbuf_size */
1972                 DRBD_RCVBUF_SIZE_DEF, /* rcvbuf_size */
1973                 DRBD_KO_COUNT_DEF, /* ko_count */
1974                 DRBD_MAX_BUFFERS_DEF, /* max_buffers */
1975                 DRBD_MAX_EPOCH_SIZE_DEF, /* max_epoch_size */
1976                 DRBD_UNPLUG_WATERMARK_DEF, /* unplug_watermark */
1977                 DRBD_AFTER_SB_0P_DEF, /* after_sb_0p */
1978                 DRBD_AFTER_SB_1P_DEF, /* after_sb_1p */
1979                 DRBD_AFTER_SB_2P_DEF, /* after_sb_2p */
1980                 DRBD_RR_CONFLICT_DEF, /* rr_conflict */
1981                 DRBD_ON_CONGESTION_DEF, /* on_congestion */
1982                 DRBD_CONG_FILL_DEF, /* cong_fill */
1983                 DRBD_CONG_EXTENTS_DEF, /* cong_extents */
1984                 0, /* two_primaries */
1985                 0, /* want_lose */
1986                 0, /* no_cork */
1987                 0, /* always_asbp */
1988                 0, /* dry_run */
1989                 0, /* use_rle */
1990         };
1991
1992         err = net_conf_from_attrs(new_conf, info);
1993         if (err) {
1994                 retcode = ERR_MANDATORY_TAG;
1995                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1996                 goto fail;
1997         }
1998
1999         retcode = check_net_options(tconn, new_conf);
2000         if (retcode != NO_ERROR)
2001                 goto fail;
2002
2003         retcode = NO_ERROR;
2004
2005         new_my_addr = (struct sockaddr *)&new_conf->my_addr;
2006         new_peer_addr = (struct sockaddr *)&new_conf->peer_addr;
2007
2008         /* No need to take drbd_cfg_rwsem here.  All reconfiguration is
2009          * strictly serialized on genl_lock(). We are protected against
2010          * concurrent reconfiguration/addition/deletion */
2011         list_for_each_entry(oconn, &drbd_tconns, all_tconn) {
2012                 struct net_conf *nc;
2013                 if (oconn == tconn)
2014                         continue;
2015
2016                 rcu_read_lock();
2017                 nc = rcu_dereference(oconn->net_conf);
2018                 if (nc) {
2019                         taken_addr = (struct sockaddr *)&nc->my_addr;
2020                         if (new_conf->my_addr_len == nc->my_addr_len &&
2021                             !memcmp(new_my_addr, taken_addr, new_conf->my_addr_len))
2022                                 retcode = ERR_LOCAL_ADDR;
2023
2024                         taken_addr = (struct sockaddr *)&nc->peer_addr;
2025                         if (new_conf->peer_addr_len == nc->peer_addr_len &&
2026                             !memcmp(new_peer_addr, taken_addr, new_conf->peer_addr_len))
2027                                 retcode = ERR_PEER_ADDR;
2028                 }
2029                 rcu_read_unlock();
2030                 if (retcode != NO_ERROR)
2031                         goto fail;
2032         }
2033
2034         retcode = alloc_crypto(&crypto, new_conf);
2035         if (retcode != NO_ERROR)
2036                 goto fail;
2037
2038         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2039
2040         conn_flush_workqueue(tconn);
2041
2042         mutex_lock(&tconn->net_conf_update);
2043         old_conf = tconn->net_conf;
2044         if (old_conf) {
2045                 retcode = ERR_NET_CONFIGURED;
2046                 mutex_unlock(&tconn->net_conf_update);
2047                 goto fail;
2048         }
2049         rcu_assign_pointer(tconn->net_conf, new_conf);
2050
2051         conn_free_crypto(tconn);
2052         tconn->int_dig_in = crypto.int_dig_in;
2053         tconn->int_dig_vv = crypto.int_dig_vv;
2054         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2055         tconn->integrity_w_tfm = crypto.integrity_w_tfm;
2056         tconn->integrity_r_tfm = crypto.integrity_r_tfm;
2057         tconn->csums_tfm = crypto.csums_tfm;
2058         tconn->verify_tfm = crypto.verify_tfm;
2059
2060         mutex_unlock(&tconn->net_conf_update);
2061
2062         rcu_read_lock();
2063         idr_for_each_entry(&tconn->volumes, mdev, i) {
2064                 mdev->send_cnt = 0;
2065                 mdev->recv_cnt = 0;
2066         }
2067         rcu_read_unlock();
2068
2069         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2070
2071         conn_reconfig_done(tconn);
2072         drbd_adm_finish(info, retcode);
2073         return 0;
2074
2075 fail:
2076         free_crypto(&crypto);
2077         kfree(new_conf);
2078
2079         conn_reconfig_done(tconn);
2080 out:
2081         drbd_adm_finish(info, retcode);
2082         return 0;
2083 }
2084
2085 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2086 {
2087         enum drbd_state_rv rv;
2088         if (force) {
2089                 spin_lock_irq(&tconn->req_lock);
2090                 rv = _conn_request_state(tconn, NS(conn, C_DISCONNECTING), CS_HARD);
2091                 spin_unlock_irq(&tconn->req_lock);
2092                 return rv;
2093         }
2094
2095         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING), 0);
2096
2097         switch (rv) {
2098         case SS_NOTHING_TO_DO:
2099         case SS_ALREADY_STANDALONE:
2100                 return SS_SUCCESS;
2101         case SS_PRIMARY_NOP:
2102                 /* Our state checking code wants to see the peer outdated. */
2103                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2104                                                         pdsk, D_OUTDATED), CS_VERBOSE);
2105                 break;
2106         case SS_CW_FAILED_BY_PEER:
2107                 /* The peer probably wants to see us outdated. */
2108                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2109                                                         disk, D_OUTDATED), 0);
2110                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2111                         conn_request_state(tconn, NS(conn, C_DISCONNECTING), CS_HARD);
2112                         rv = SS_SUCCESS;
2113                 }
2114                 break;
2115         default:;
2116                 /* no special handling necessary */
2117         }
2118
2119         return rv;
2120 }
2121
2122 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2123 {
2124         struct disconnect_parms parms;
2125         struct drbd_tconn *tconn;
2126         enum drbd_state_rv rv;
2127         enum drbd_ret_code retcode;
2128         int err;
2129
2130         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2131         if (!adm_ctx.reply_skb)
2132                 return retcode;
2133         if (retcode != NO_ERROR)
2134                 goto fail;
2135
2136         tconn = adm_ctx.tconn;
2137         memset(&parms, 0, sizeof(parms));
2138         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2139                 err = disconnect_parms_from_attrs(&parms, info);
2140                 if (err) {
2141                         retcode = ERR_MANDATORY_TAG;
2142                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2143                         goto fail;
2144                 }
2145         }
2146
2147         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2148         if (rv < SS_SUCCESS)
2149                 goto fail;
2150
2151         /* No one else can reconfigure the network while I am here.
2152          * The state handling only uses drbd_thread_stop_nowait(),
2153          * we want to really wait here until the receiver is no more. */
2154         drbd_thread_stop(&tconn->receiver);
2155         if (wait_event_interruptible(tconn->ping_wait,
2156                                      tconn->cstate == C_STANDALONE)) {
2157                 retcode = ERR_INTR;
2158                 goto fail;
2159         }
2160
2161         retcode = NO_ERROR;
2162  fail:
2163         drbd_adm_finish(info, retcode);
2164         return 0;
2165 }
2166
2167 void resync_after_online_grow(struct drbd_conf *mdev)
2168 {
2169         int iass; /* I am sync source */
2170
2171         dev_info(DEV, "Resync of new storage after online grow\n");
2172         if (mdev->state.role != mdev->state.peer)
2173                 iass = (mdev->state.role == R_PRIMARY);
2174         else
2175                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2176
2177         if (iass)
2178                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2179         else
2180                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2181 }
2182
2183 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2184 {
2185         struct resize_parms rs;
2186         struct drbd_conf *mdev;
2187         enum drbd_ret_code retcode;
2188         enum determine_dev_size dd;
2189         enum dds_flags ddsf;
2190         int err;
2191
2192         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2193         if (!adm_ctx.reply_skb)
2194                 return retcode;
2195         if (retcode != NO_ERROR)
2196                 goto fail;
2197
2198         memset(&rs, 0, sizeof(struct resize_parms));
2199         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2200                 err = resize_parms_from_attrs(&rs, info);
2201                 if (err) {
2202                         retcode = ERR_MANDATORY_TAG;
2203                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2204                         goto fail;
2205                 }
2206         }
2207
2208         mdev = adm_ctx.mdev;
2209         if (mdev->state.conn > C_CONNECTED) {
2210                 retcode = ERR_RESIZE_RESYNC;
2211                 goto fail;
2212         }
2213
2214         if (mdev->state.role == R_SECONDARY &&
2215             mdev->state.peer == R_SECONDARY) {
2216                 retcode = ERR_NO_PRIMARY;
2217                 goto fail;
2218         }
2219
2220         if (!get_ldev(mdev)) {
2221                 retcode = ERR_NO_DISK;
2222                 goto fail;
2223         }
2224
2225         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2226                 retcode = ERR_NEED_APV_93;
2227                 goto fail;
2228         }
2229
2230         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2231                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2232
2233         mdev->ldev->dc.disk_size = (sector_t)rs.resize_size;
2234         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2235         dd = drbd_determine_dev_size(mdev, ddsf);
2236         drbd_md_sync(mdev);
2237         put_ldev(mdev);
2238         if (dd == dev_size_error) {
2239                 retcode = ERR_NOMEM_BITMAP;
2240                 goto fail;
2241         }
2242
2243         if (mdev->state.conn == C_CONNECTED) {
2244                 if (dd == grew)
2245                         set_bit(RESIZE_PENDING, &mdev->flags);
2246
2247                 drbd_send_uuids(mdev);
2248                 drbd_send_sizes(mdev, 1, ddsf);
2249         }
2250
2251  fail:
2252         drbd_adm_finish(info, retcode);
2253         return 0;
2254 }
2255
2256 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2257 {
2258         enum drbd_ret_code retcode;
2259         cpumask_var_t new_cpu_mask;
2260         struct drbd_tconn *tconn;
2261         int *rs_plan_s = NULL;
2262         struct res_opts sc;
2263         int err;
2264
2265         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2266         if (!adm_ctx.reply_skb)
2267                 return retcode;
2268         if (retcode != NO_ERROR)
2269                 goto fail;
2270         tconn = adm_ctx.tconn;
2271
2272         if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) {
2273                 retcode = ERR_NOMEM;
2274                 drbd_msg_put_info("unable to allocate cpumask");
2275                 goto fail;
2276         }
2277
2278         if (((struct drbd_genlmsghdr*)info->userhdr)->flags
2279                         & DRBD_GENL_F_SET_DEFAULTS) {
2280                 memset(&sc, 0, sizeof(struct res_opts));
2281                 sc.on_no_data  = DRBD_ON_NO_DATA_DEF;
2282         } else
2283                 sc = tconn->res_opts;
2284
2285         err = res_opts_from_attrs(&sc, info);
2286         if (err) {
2287                 retcode = ERR_MANDATORY_TAG;
2288                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2289                 goto fail;
2290         }
2291
2292         /* silently ignore cpu mask on UP kernel */
2293         if (nr_cpu_ids > 1 && sc.cpu_mask[0] != 0) {
2294                 err = __bitmap_parse(sc.cpu_mask, 32, 0,
2295                                 cpumask_bits(new_cpu_mask), nr_cpu_ids);
2296                 if (err) {
2297                         conn_warn(tconn, "__bitmap_parse() failed with %d\n", err);
2298                         retcode = ERR_CPU_MASK_PARSE;
2299                         goto fail;
2300                 }
2301         }
2302
2303
2304         tconn->res_opts = sc;
2305
2306         if (!cpumask_equal(tconn->cpu_mask, new_cpu_mask)) {
2307                 cpumask_copy(tconn->cpu_mask, new_cpu_mask);
2308                 drbd_calc_cpu_mask(tconn);
2309                 tconn->receiver.reset_cpu_mask = 1;
2310                 tconn->asender.reset_cpu_mask = 1;
2311                 tconn->worker.reset_cpu_mask = 1;
2312         }
2313
2314 fail:
2315         kfree(rs_plan_s);
2316         free_cpumask_var(new_cpu_mask);
2317
2318         drbd_adm_finish(info, retcode);
2319         return 0;
2320 }
2321
2322 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2323 {
2324         struct drbd_conf *mdev;
2325         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2326
2327         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2328         if (!adm_ctx.reply_skb)
2329                 return retcode;
2330         if (retcode != NO_ERROR)
2331                 goto out;
2332
2333         mdev = adm_ctx.mdev;
2334
2335         /* If there is still bitmap IO pending, probably because of a previous
2336          * resync just being finished, wait for it before requesting a new resync. */
2337         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2338
2339         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2340
2341         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2342                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2343
2344         while (retcode == SS_NEED_CONNECTION) {
2345                 spin_lock_irq(&mdev->tconn->req_lock);
2346                 if (mdev->state.conn < C_CONNECTED)
2347                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2348                 spin_unlock_irq(&mdev->tconn->req_lock);
2349
2350                 if (retcode != SS_NEED_CONNECTION)
2351                         break;
2352
2353                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2354         }
2355
2356 out:
2357         drbd_adm_finish(info, retcode);
2358         return 0;
2359 }
2360
2361 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2362 {
2363         int rv;
2364
2365         rv = drbd_bmio_set_n_write(mdev);
2366         drbd_suspend_al(mdev);
2367         return rv;
2368 }
2369
2370 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2371                 union drbd_state mask, union drbd_state val)
2372 {
2373         enum drbd_ret_code retcode;
2374
2375         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2376         if (!adm_ctx.reply_skb)
2377                 return retcode;
2378         if (retcode != NO_ERROR)
2379                 goto out;
2380
2381         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2382 out:
2383         drbd_adm_finish(info, retcode);
2384         return 0;
2385 }
2386
2387 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2388 {
2389         return drbd_adm_simple_request_state(skb, info, NS(conn, C_STARTING_SYNC_S));
2390 }
2391
2392 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2393 {
2394         enum drbd_ret_code retcode;
2395
2396         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2397         if (!adm_ctx.reply_skb)
2398                 return retcode;
2399         if (retcode != NO_ERROR)
2400                 goto out;
2401
2402         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2403                 retcode = ERR_PAUSE_IS_SET;
2404 out:
2405         drbd_adm_finish(info, retcode);
2406         return 0;
2407 }
2408
2409 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2410 {
2411         union drbd_dev_state s;
2412         enum drbd_ret_code retcode;
2413
2414         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2415         if (!adm_ctx.reply_skb)
2416                 return retcode;
2417         if (retcode != NO_ERROR)
2418                 goto out;
2419
2420         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2421                 s = adm_ctx.mdev->state;
2422                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2423                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2424                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2425                 } else {
2426                         retcode = ERR_PAUSE_IS_CLEAR;
2427                 }
2428         }
2429
2430 out:
2431         drbd_adm_finish(info, retcode);
2432         return 0;
2433 }
2434
2435 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2436 {
2437         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2438 }
2439
2440 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2441 {
2442         struct drbd_conf *mdev;
2443         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2444
2445         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2446         if (!adm_ctx.reply_skb)
2447                 return retcode;
2448         if (retcode != NO_ERROR)
2449                 goto out;
2450
2451         mdev = adm_ctx.mdev;
2452         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2453                 drbd_uuid_new_current(mdev);
2454                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2455         }
2456         drbd_suspend_io(mdev);
2457         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2458         if (retcode == SS_SUCCESS) {
2459                 if (mdev->state.conn < C_CONNECTED)
2460                         tl_clear(mdev->tconn);
2461                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2462                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2463         }
2464         drbd_resume_io(mdev);
2465
2466 out:
2467         drbd_adm_finish(info, retcode);
2468         return 0;
2469 }
2470
2471 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2472 {
2473         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2474 }
2475
2476 int nla_put_drbd_cfg_context(struct sk_buff *skb, const char *conn_name, unsigned vnr)
2477 {
2478         struct nlattr *nla;
2479         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2480         if (!nla)
2481                 goto nla_put_failure;
2482         if (vnr != VOLUME_UNSPECIFIED)
2483                 NLA_PUT_U32(skb, T_ctx_volume, vnr);
2484         NLA_PUT_STRING(skb, T_ctx_conn_name, conn_name);
2485         nla_nest_end(skb, nla);
2486         return 0;
2487
2488 nla_put_failure:
2489         if (nla)
2490                 nla_nest_cancel(skb, nla);
2491         return -EMSGSIZE;
2492 }
2493
2494 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2495                 const struct sib_info *sib)
2496 {
2497         struct state_info *si = NULL; /* for sizeof(si->member); */
2498         struct net_conf *nc;
2499         struct nlattr *nla;
2500         int got_ldev;
2501         int err = 0;
2502         int exclude_sensitive;
2503
2504         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2505          * to.  So we better exclude_sensitive information.
2506          *
2507          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2508          * in the context of the requesting user process. Exclude sensitive
2509          * information, unless current has superuser.
2510          *
2511          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2512          * relies on the current implementation of netlink_dump(), which
2513          * executes the dump callback successively from netlink_recvmsg(),
2514          * always in the context of the receiving process */
2515         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2516
2517         got_ldev = get_ldev(mdev);
2518
2519         /* We need to add connection name and volume number information still.
2520          * Minor number is in drbd_genlmsghdr. */
2521         if (nla_put_drbd_cfg_context(skb, mdev->tconn->name, mdev->vnr))
2522                 goto nla_put_failure;
2523
2524         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2525                 goto nla_put_failure;
2526
2527         if (got_ldev)
2528                 if (disk_conf_to_skb(skb, &mdev->ldev->dc, exclude_sensitive))
2529                         goto nla_put_failure;
2530
2531         rcu_read_lock();
2532         nc = rcu_dereference(mdev->tconn->net_conf);
2533         if (nc)
2534                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2535         rcu_read_unlock();
2536         if (err)
2537                 goto nla_put_failure;
2538
2539         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2540         if (!nla)
2541                 goto nla_put_failure;
2542         NLA_PUT_U32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY);
2543         NLA_PUT_U32(skb, T_current_state, mdev->state.i);
2544         NLA_PUT_U64(skb, T_ed_uuid, mdev->ed_uuid);
2545         NLA_PUT_U64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev));
2546
2547         if (got_ldev) {
2548                 NLA_PUT_U32(skb, T_disk_flags, mdev->ldev->md.flags);
2549                 NLA_PUT(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2550                 NLA_PUT_U64(skb, T_bits_total, drbd_bm_bits(mdev));
2551                 NLA_PUT_U64(skb, T_bits_oos, drbd_bm_total_weight(mdev));
2552                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2553                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2554                         NLA_PUT_U64(skb, T_bits_rs_total, mdev->rs_total);
2555                         NLA_PUT_U64(skb, T_bits_rs_failed, mdev->rs_failed);
2556                 }
2557         }
2558
2559         if (sib) {
2560                 switch(sib->sib_reason) {
2561                 case SIB_SYNC_PROGRESS:
2562                 case SIB_GET_STATUS_REPLY:
2563                         break;
2564                 case SIB_STATE_CHANGE:
2565                         NLA_PUT_U32(skb, T_prev_state, sib->os.i);
2566                         NLA_PUT_U32(skb, T_new_state, sib->ns.i);
2567                         break;
2568                 case SIB_HELPER_POST:
2569                         NLA_PUT_U32(skb,
2570                                 T_helper_exit_code, sib->helper_exit_code);
2571                         /* fall through */
2572                 case SIB_HELPER_PRE:
2573                         NLA_PUT_STRING(skb, T_helper, sib->helper_name);
2574                         break;
2575                 }
2576         }
2577         nla_nest_end(skb, nla);
2578
2579         if (0)
2580 nla_put_failure:
2581                 err = -EMSGSIZE;
2582         if (got_ldev)
2583                 put_ldev(mdev);
2584         return err;
2585 }
2586
2587 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2588 {
2589         enum drbd_ret_code retcode;
2590         int err;
2591
2592         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2593         if (!adm_ctx.reply_skb)
2594                 return retcode;
2595         if (retcode != NO_ERROR)
2596                 goto out;
2597
2598         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2599         if (err) {
2600                 nlmsg_free(adm_ctx.reply_skb);
2601                 return err;
2602         }
2603 out:
2604         drbd_adm_finish(info, retcode);
2605         return 0;
2606 }
2607
2608 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2609 {
2610         struct drbd_conf *mdev;
2611         struct drbd_genlmsghdr *dh;
2612         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2613         struct drbd_tconn *tconn = NULL;
2614         struct drbd_tconn *tmp;
2615         unsigned volume = cb->args[1];
2616
2617         /* Open coded, deferred, iteration:
2618          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2619          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2620          *        ...
2621          *      }
2622          * }
2623          * where tconn is cb->args[0];
2624          * and i is cb->args[1];
2625          *
2626          * cb->args[2] indicates if we shall loop over all resources,
2627          * or just dump all volumes of a single resource.
2628          *
2629          * This may miss entries inserted after this dump started,
2630          * or entries deleted before they are reached.
2631          *
2632          * We need to make sure the mdev won't disappear while
2633          * we are looking at it, and revalidate our iterators
2634          * on each iteration.
2635          */
2636
2637         /* synchronize with conn_create()/conn_destroy() */
2638         down_read(&drbd_cfg_rwsem);
2639         /* revalidate iterator position */
2640         list_for_each_entry(tmp, &drbd_tconns, all_tconn) {
2641                 if (pos == NULL) {
2642                         /* first iteration */
2643                         pos = tmp;
2644                         tconn = pos;
2645                         break;
2646                 }
2647                 if (tmp == pos) {
2648                         tconn = pos;
2649                         break;
2650                 }
2651         }
2652         if (tconn) {
2653 next_tconn:
2654                 mdev = idr_get_next(&tconn->volumes, &volume);
2655                 if (!mdev) {
2656                         /* No more volumes to dump on this tconn.
2657                          * Advance tconn iterator. */
2658                         pos = list_entry(tconn->all_tconn.next,
2659                                         struct drbd_tconn, all_tconn);
2660                         /* Did we dump any volume on this tconn yet? */
2661                         if (volume != 0) {
2662                                 /* If we reached the end of the list,
2663                                  * or only a single resource dump was requested,
2664                                  * we are done. */
2665                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2666                                         goto out;
2667                                 volume = 0;
2668                                 tconn = pos;
2669                                 goto next_tconn;
2670                         }
2671                 }
2672
2673                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2674                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2675                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2676                 if (!dh)
2677                         goto out;
2678
2679                 if (!mdev) {
2680                         /* this is a tconn without a single volume */
2681                         dh->minor = -1U;
2682                         dh->ret_code = NO_ERROR;
2683                         if (nla_put_drbd_cfg_context(skb, tconn->name, VOLUME_UNSPECIFIED))
2684                                 genlmsg_cancel(skb, dh);
2685                         else
2686                                 genlmsg_end(skb, dh);
2687                         goto out;
2688                 }
2689
2690                 D_ASSERT(mdev->vnr == volume);
2691                 D_ASSERT(mdev->tconn == tconn);
2692
2693                 dh->minor = mdev_to_minor(mdev);
2694                 dh->ret_code = NO_ERROR;
2695
2696                 if (nla_put_status_info(skb, mdev, NULL)) {
2697                         genlmsg_cancel(skb, dh);
2698                         goto out;
2699                 }
2700                 genlmsg_end(skb, dh);
2701         }
2702
2703 out:
2704         up_read(&drbd_cfg_rwsem);
2705         /* where to start the next iteration */
2706         cb->args[0] = (long)pos;
2707         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2708
2709         /* No more tconns/volumes/minors found results in an empty skb.
2710          * Which will terminate the dump. */
2711         return skb->len;
2712 }
2713
2714 /*
2715  * Request status of all resources, or of all volumes within a single resource.
2716  *
2717  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2718  * Which means we cannot use the family->attrbuf or other such members, because
2719  * dump is NOT protected by the genl_lock().  During dump, we only have access
2720  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2721  *
2722  * Once things are setup properly, we call into get_one_status().
2723  */
2724 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2725 {
2726         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2727         struct nlattr *nla;
2728         const char *conn_name;
2729         struct drbd_tconn *tconn;
2730
2731         /* Is this a followup call? */
2732         if (cb->args[0]) {
2733                 /* ... of a single resource dump,
2734                  * and the resource iterator has been advanced already? */
2735                 if (cb->args[2] && cb->args[2] != cb->args[0])
2736                         return 0; /* DONE. */
2737                 goto dump;
2738         }
2739
2740         /* First call (from netlink_dump_start).  We need to figure out
2741          * which resource(s) the user wants us to dump. */
2742         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2743                         nlmsg_attrlen(cb->nlh, hdrlen),
2744                         DRBD_NLA_CFG_CONTEXT);
2745
2746         /* No explicit context given.  Dump all. */
2747         if (!nla)
2748                 goto dump;
2749         nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
2750         /* context given, but no name present? */
2751         if (!nla)
2752                 return -EINVAL;
2753         conn_name = nla_data(nla);
2754         tconn = conn_get_by_name(conn_name);
2755
2756         if (!tconn)
2757                 return -ENODEV;
2758
2759         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2760
2761         /* prime iterators, and set "filter" mode mark:
2762          * only dump this tconn. */
2763         cb->args[0] = (long)tconn;
2764         /* cb->args[1] = 0; passed in this way. */
2765         cb->args[2] = (long)tconn;
2766
2767 dump:
2768         return get_one_status(skb, cb);
2769 }
2770
2771 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2772 {
2773         enum drbd_ret_code retcode;
2774         struct timeout_parms tp;
2775         int err;
2776
2777         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2778         if (!adm_ctx.reply_skb)
2779                 return retcode;
2780         if (retcode != NO_ERROR)
2781                 goto out;
2782
2783         tp.timeout_type =
2784                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2785                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2786                 UT_DEFAULT;
2787
2788         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2789         if (err) {
2790                 nlmsg_free(adm_ctx.reply_skb);
2791                 return err;
2792         }
2793 out:
2794         drbd_adm_finish(info, retcode);
2795         return 0;
2796 }
2797
2798 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2799 {
2800         struct drbd_conf *mdev;
2801         enum drbd_ret_code retcode;
2802
2803         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2804         if (!adm_ctx.reply_skb)
2805                 return retcode;
2806         if (retcode != NO_ERROR)
2807                 goto out;
2808
2809         mdev = adm_ctx.mdev;
2810         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2811                 /* resume from last known position, if possible */
2812                 struct start_ov_parms parms =
2813                         { .ov_start_sector = mdev->ov_start_sector };
2814                 int err = start_ov_parms_from_attrs(&parms, info);
2815                 if (err) {
2816                         retcode = ERR_MANDATORY_TAG;
2817                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2818                         goto out;
2819                 }
2820                 /* w_make_ov_request expects position to be aligned */
2821                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2822         }
2823         /* If there is still bitmap IO pending, e.g. previous resync or verify
2824          * just being finished, wait for it before requesting a new resync. */
2825         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2826         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2827 out:
2828         drbd_adm_finish(info, retcode);
2829         return 0;
2830 }
2831
2832
2833 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2834 {
2835         struct drbd_conf *mdev;
2836         enum drbd_ret_code retcode;
2837         int skip_initial_sync = 0;
2838         int err;
2839         struct new_c_uuid_parms args;
2840
2841         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2842         if (!adm_ctx.reply_skb)
2843                 return retcode;
2844         if (retcode != NO_ERROR)
2845                 goto out_nolock;
2846
2847         mdev = adm_ctx.mdev;
2848         memset(&args, 0, sizeof(args));
2849         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2850                 err = new_c_uuid_parms_from_attrs(&args, info);
2851                 if (err) {
2852                         retcode = ERR_MANDATORY_TAG;
2853                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2854                         goto out_nolock;
2855                 }
2856         }
2857
2858         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2859
2860         if (!get_ldev(mdev)) {
2861                 retcode = ERR_NO_DISK;
2862                 goto out;
2863         }
2864
2865         /* this is "skip initial sync", assume to be clean */
2866         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2867             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2868                 dev_info(DEV, "Preparing to skip initial sync\n");
2869                 skip_initial_sync = 1;
2870         } else if (mdev->state.conn != C_STANDALONE) {
2871                 retcode = ERR_CONNECTED;
2872                 goto out_dec;
2873         }
2874
2875         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2876         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2877
2878         if (args.clear_bm) {
2879                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2880                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2881                 if (err) {
2882                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2883                         retcode = ERR_IO_MD_DISK;
2884                 }
2885                 if (skip_initial_sync) {
2886                         drbd_send_uuids_skip_initial_sync(mdev);
2887                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
2888                         drbd_print_uuids(mdev, "cleared bitmap UUID");
2889                         spin_lock_irq(&mdev->tconn->req_lock);
2890                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2891                                         CS_VERBOSE, NULL);
2892                         spin_unlock_irq(&mdev->tconn->req_lock);
2893                 }
2894         }
2895
2896         drbd_md_sync(mdev);
2897 out_dec:
2898         put_ldev(mdev);
2899 out:
2900         mutex_unlock(mdev->state_mutex);
2901 out_nolock:
2902         drbd_adm_finish(info, retcode);
2903         return 0;
2904 }
2905
2906 static enum drbd_ret_code
2907 drbd_check_conn_name(const char *name)
2908 {
2909         if (!name || !name[0]) {
2910                 drbd_msg_put_info("connection name missing");
2911                 return ERR_MANDATORY_TAG;
2912         }
2913         /* if we want to use these in sysfs/configfs/debugfs some day,
2914          * we must not allow slashes */
2915         if (strchr(name, '/')) {
2916                 drbd_msg_put_info("invalid connection name");
2917                 return ERR_INVALID_REQUEST;
2918         }
2919         return NO_ERROR;
2920 }
2921
2922 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info)
2923 {
2924         enum drbd_ret_code retcode;
2925
2926         retcode = drbd_adm_prepare(skb, info, 0);
2927         if (!adm_ctx.reply_skb)
2928                 return retcode;
2929         if (retcode != NO_ERROR)
2930                 goto out;
2931
2932         retcode = drbd_check_conn_name(adm_ctx.conn_name);
2933         if (retcode != NO_ERROR)
2934                 goto out;
2935
2936         if (adm_ctx.tconn) {
2937                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
2938                         retcode = ERR_INVALID_REQUEST;
2939                         drbd_msg_put_info("connection exists");
2940                 }
2941                 /* else: still NO_ERROR */
2942                 goto out;
2943         }
2944
2945         if (!conn_create(adm_ctx.conn_name))
2946                 retcode = ERR_NOMEM;
2947 out:
2948         drbd_adm_finish(info, retcode);
2949         return 0;
2950 }
2951
2952 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
2953 {
2954         struct drbd_genlmsghdr *dh = info->userhdr;
2955         enum drbd_ret_code retcode;
2956
2957         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2958         if (!adm_ctx.reply_skb)
2959                 return retcode;
2960         if (retcode != NO_ERROR)
2961                 goto out;
2962
2963         /* FIXME drop minor_count parameter, limit to MINORMASK */
2964         if (dh->minor >= minor_count) {
2965                 drbd_msg_put_info("requested minor out of range");
2966                 retcode = ERR_INVALID_REQUEST;
2967                 goto out;
2968         }
2969         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
2970                 drbd_msg_put_info("requested volume id out of range");
2971                 retcode = ERR_INVALID_REQUEST;
2972                 goto out;
2973         }
2974
2975         /* drbd_adm_prepare made sure already
2976          * that mdev->tconn and mdev->vnr match the request. */
2977         if (adm_ctx.mdev) {
2978                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
2979                         retcode = ERR_MINOR_EXISTS;
2980                 /* else: still NO_ERROR */
2981                 goto out;
2982         }
2983
2984         down_write(&drbd_cfg_rwsem);
2985         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
2986         up_write(&drbd_cfg_rwsem);
2987 out:
2988         drbd_adm_finish(info, retcode);
2989         return 0;
2990 }
2991
2992 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
2993 {
2994         if (mdev->state.disk == D_DISKLESS &&
2995             /* no need to be mdev->state.conn == C_STANDALONE &&
2996              * we may want to delete a minor from a live replication group.
2997              */
2998             mdev->state.role == R_SECONDARY) {
2999                 drbd_delete_device(mdev);
3000                 return NO_ERROR;
3001         } else
3002                 return ERR_MINOR_CONFIGURED;
3003 }
3004
3005 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3006 {
3007         enum drbd_ret_code retcode;
3008
3009         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3010         if (!adm_ctx.reply_skb)
3011                 return retcode;
3012         if (retcode != NO_ERROR)
3013                 goto out;
3014
3015         down_write(&drbd_cfg_rwsem);
3016         retcode = adm_delete_minor(adm_ctx.mdev);
3017         up_write(&drbd_cfg_rwsem);
3018 out:
3019         drbd_adm_finish(info, retcode);
3020         return 0;
3021 }
3022
3023 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3024 {
3025         enum drbd_ret_code retcode;
3026         enum drbd_state_rv rv;
3027         struct drbd_conf *mdev;
3028         unsigned i;
3029
3030         retcode = drbd_adm_prepare(skb, info, 0);
3031         if (!adm_ctx.reply_skb)
3032                 return retcode;
3033         if (retcode != NO_ERROR)
3034                 goto out;
3035
3036         if (!adm_ctx.tconn) {
3037                 retcode = ERR_CONN_NOT_KNOWN;
3038                 goto out;
3039         }
3040
3041         down_read(&drbd_cfg_rwsem);
3042         /* demote */
3043         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3044                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3045                 if (retcode < SS_SUCCESS) {
3046                         drbd_msg_put_info("failed to demote");
3047                         goto out_unlock;
3048                 }
3049         }
3050
3051         /* disconnect */
3052         rv = conn_try_disconnect(adm_ctx.tconn, 0);
3053         if (rv < SS_SUCCESS) {
3054                 retcode = rv; /* enum type mismatch! */
3055                 drbd_msg_put_info("failed to disconnect");
3056                 goto out_unlock;
3057         }
3058
3059         /* Make sure the network threads have actually stopped,
3060          * state handling only does drbd_thread_stop_nowait(). */
3061         drbd_thread_stop(&adm_ctx.tconn->receiver);
3062
3063         /* detach */
3064         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3065                 rv = adm_detach(mdev);
3066                 if (rv < SS_SUCCESS) {
3067                         retcode = rv; /* enum type mismatch! */
3068                         drbd_msg_put_info("failed to detach");
3069                         goto out_unlock;
3070                 }
3071         }
3072         up_read(&drbd_cfg_rwsem);
3073
3074         /* delete volumes */
3075         down_write(&drbd_cfg_rwsem);
3076         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3077                 retcode = adm_delete_minor(mdev);
3078                 if (retcode != NO_ERROR) {
3079                         /* "can not happen" */
3080                         drbd_msg_put_info("failed to delete volume");
3081                         up_write(&drbd_cfg_rwsem);
3082                         goto out;
3083                 }
3084         }
3085
3086         /* delete connection */
3087         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3088                 drbd_thread_stop(&adm_ctx.tconn->worker);
3089                 list_del(&adm_ctx.tconn->all_tconn);
3090                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3091
3092                 retcode = NO_ERROR;
3093         } else {
3094                 /* "can not happen" */
3095                 retcode = ERR_CONN_IN_USE;
3096                 drbd_msg_put_info("failed to delete connection");
3097         }
3098
3099         up_write(&drbd_cfg_rwsem);
3100         goto out;
3101 out_unlock:
3102         up_read(&drbd_cfg_rwsem);
3103 out:
3104         drbd_adm_finish(info, retcode);
3105         return 0;
3106 }
3107
3108 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info)
3109 {
3110         enum drbd_ret_code retcode;
3111
3112         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
3113         if (!adm_ctx.reply_skb)
3114                 return retcode;
3115         if (retcode != NO_ERROR)
3116                 goto out;
3117
3118         down_write(&drbd_cfg_rwsem);
3119         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3120                 list_del(&adm_ctx.tconn->all_tconn);
3121                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3122
3123                 retcode = NO_ERROR;
3124         } else {
3125                 retcode = ERR_CONN_IN_USE;
3126         }
3127         up_write(&drbd_cfg_rwsem);
3128
3129 out:
3130         drbd_adm_finish(info, retcode);
3131         return 0;
3132 }
3133
3134 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3135 {
3136         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3137         struct sk_buff *msg;
3138         struct drbd_genlmsghdr *d_out;
3139         unsigned seq;
3140         int err = -ENOMEM;
3141
3142         seq = atomic_inc_return(&drbd_genl_seq);
3143         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3144         if (!msg)
3145                 goto failed;
3146
3147         err = -EMSGSIZE;
3148         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3149         if (!d_out) /* cannot happen, but anyways. */
3150                 goto nla_put_failure;
3151         d_out->minor = mdev_to_minor(mdev);
3152         d_out->ret_code = 0;
3153
3154         if (nla_put_status_info(msg, mdev, sib))
3155                 goto nla_put_failure;
3156         genlmsg_end(msg, d_out);
3157         err = drbd_genl_multicast_events(msg, 0);
3158         /* msg has been consumed or freed in netlink_broadcast() */
3159         if (err && err != -ESRCH)
3160                 goto failed;
3161
3162         return;
3163
3164 nla_put_failure:
3165         nlmsg_free(msg);
3166 failed:
3167         dev_err(DEV, "Error %d while broadcasting event. "
3168                         "Event seq:%u sib_reason:%u\n",
3169                         err, seq, sib->sib_reason);
3170 }