OSDN Git Service

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